4

I'm not sure how much of the code I can show, but the concept is simple. I am writing a python script that works with the TD Ameritrade API. I am getting a url for the portal from the API, and opening it in the browser. Next, I'm setting up a socket server to handle the redirect of the portal. Below is the code for the server:

serversocket = socket.socket(
                socket.AF_INET, socket.SOCK_STREAM) 

    # get local machine name
    host = "localhost"                 

    port = 10120                                          
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # bind to the port
    serversocket.bind((host, port))                                  

    print("listening")
    # queue up to 5 requests
    serversocket.listen(5)                                           

    allData = ""

    while True:
        # establish a connection
        try:
            conn,addr = serversocket.accept()
        except KeyboardInterrupt:
            break  

        print("Got a connection from %s" % str(addr))
        while True:
            data = conn.recv(4096)

            if not data:
                print("done")
                break

            print(data.decode('utf-8', "ignore"))
        conn.close()

When I go through the portal and get redirected, in the console I see the following:

Got a connection from ('127.0.0.1', 65505)                                                                              
  |,?2!c[N': [?`XAn] "::+/,0̨̩   / 5                                                              
 jj         localhost                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
     3 + )http/1.1                                                                                                                                                                                                               
    ej\E<zpִ_<%q\r)+ -  +                                                                                   
jj   zz   

However, if I were to copy the URL, open a new tab, paste it and go, I get the following (correct) response:

Got a connection from ('127.0.0.1', 49174)                                                                              
GET /?code=<RESPONSE_TOKEN> HTTP/1.1                                                               
Host: localhost:10120                                                                                                   
Connection: keep-alive                                                                                                  
Cache-Control: max-age=0                                                                                                
Upgrade-Insecure-Requests: 1                                                                                            
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125                                                                                               
Accept: 
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-
exchange;v=b3;q=0.9                                                                                                            
Sec-Fetch-Site: none                                                                                                    
Sec-Fetch-Mode: navigate                                                                                                
Sec-Fetch-User: ?1                                                                                                      
Sec-Fetch-Dest: document                                                                                                
Accept-Encoding: gzip, deflate, br                                                                                      
Accept-Language: en-US,en;q=0.9    

When I go to the network overview of my browser, I see the following warning when trying to view the request headers: Provisional headers are shown

And the only difference between the http request from the redirect, and the request when I manually paste the url in is the initiator column in the network viewer is "oath" for the redirect, and "other" when manually pasted in.

I hope I've provided enough information and code. I can try to make a copy for reproducing if needed, but a TD Ameritrade Developer account would be needed to connect with the API.

Thanks in advance for any help. I've been researching for over 6 hours and wasn't able to find anything. Hopefully I didn't miss something obvious.

Amir Abbas
  • 49
  • 1
  • 8

1 Answers1

0

I think, socket is not required to handle an oauth redirect. Socket is for another kind of requeriments.

Also when you manually hit the redirect, a socket is not invoked. Just a simple http endpoint.

Try with this snippet which has the oauth code extract:

from urlparse import urlparse,parse_qsl
class Handler(BaseHTTPRequestHandler):

    def do_GET(self):
        url = urlparse(self.path)
        code = parse_qsl(url.query)['code']

Or this:

https://gist.github.com/willnix/daed2b57ab8d613f6bfa53c6d0b46fd3

You can get more snippets of simple http get endpoints here:

https://gist.github.com/search?q=def+do_GET+python&ref=searchresults

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
  • I tried all the snippets, but they all had the same result when the OAUTH portal redirected to them: 127.0.0.1 - - [31/May/2020 15:40:18] code 400, message Bad request syntax ('\x16\x03\x01\x02\x00\x01\x00\x01ü\x03\x03\x99kº6/\x92ù0?\x18¬\x7fò\\!\x81\x19A\x8a6ÍyÁ') 127.0.0.1 - - [31/May/2020 15:40:18] " ükº6/ù0?¬ò\!A6ÍyÁ" 400 - – Amir Abbas May 31 '20 at 19:51
  • redirection from portal is trough a browser? That log indicates that your python server receives some rare body. Oauth code redirection must be just a simple get – JRichardsz May 31 '20 at 23:37
  • Are you using this https://developer.tdameritrade.com/content/simple-auth-local-apps ? – JRichardsz May 31 '20 at 23:41
  • I'm using the python library from https://github.com/areed1192/td-ameritrade-python-api, and modifying the client.py. By default it gives you a link to copy and paste in the browser, and asks you to copy and paste the redirect link to the terminal. I want to avoid this by creating a simple server to handle it all, but i'm running into this issue. I would love to find a solution to keep doing this in python. – Amir Abbas Jun 01 '20 at 04:26