Keywords: 

If you are trying to create a local application, here is a sample of how to handle authentication over localhost with Python

If you need to change your app's Redirect URI, note that at this time, the app must be deleted and re-created.

 

What you will need

You will need the software below. The version used for this sample is shown in parentheses.

  1. Python (2.7.14) & pip (9.0.1)
  2. openssl (0.9.8h)
  3. Your app information
    1. Redirect URI
    2. OAuth User ID

Generating a self-signed certificate

The openssl command below will generate key and certificate files you will need later. Put them in a location accessible to the Node app.

openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem

Note: this is specific to apps running on the local machine, a response is sent to the browser only to show it's working.

 

Setting up the Python environment

Create a directory for this app and run the commands below

python -m pip install requests

 

The Python app

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from urlparse import parse_qs
import requests
import ssl

class Handler(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        #Get the Auth Code
        path, _, query_string = self.path.partition('?')
        code = parse_qs(query_string)['code'][0]

        #Post Access Token Request
        headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
        data = { 'grant_type': 'authorization_code', 'access_type': 'offline', 'code': code, 'client_id': 'OAuth User ID', 'redirect_uri': 'Redirect URI' }
        auth_reply = requests.post('https://api.tdameritrade.com/v1/oauth2/token', headers=headers, data=data)
        
        #returned just to test that it's working
        self.wfile.write(auth_reply.text.encode())

httpd = HTTPServer(('Host to Listen On', Port to Listen On), Handler)

httpd.socket = ssl.wrap_socket (httpd.socket,
        keyfile='path/to/key.pem',
        certfile='path/to/certificate.pem', server_side=True)

httpd.serve_forever()

Sample created referencing the Python documentation. Uses Requests.

 

Trying it out

Go to a browser and enter your app's authentication URL in the format below. Remember to URLEncode the variables before adding them to the URL

https://auth.tdameritrade.com/auth?response_type=code&redirect_uri=Redirect URI&client_id=OAuth User ID

If the app is working, you should see the Post Access Token response in the browser