Skip to content Skip to sidebar Skip to footer

How To Programmatically Retrieve Access_token From Client-side Oauth Flow Using Python?

This question was posted on StackApps, but the issue may be more a programming issue than an authentication issue, hence it may deserve a better place here. I am working on an desk

Solution 1:

The token does not appear because of the way urllib2 handles the redirect. I am not familiar with the details so I won't elaborate here.

The solution is to catch the 302 before the urllib2 handles the redirect. This can be done by sub-classing the urllib2.HTTPRedirectHandler to get the redirect with its hashtag and token. Here is a short example of subclassing the handler:

classMyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
    defhttp_error_302(self, req, fp, code, msg, headers):
        print"Going through 302:\n"print headers
        return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)

In the headers the location attribute will provide the redirect URL in full length, i.e. including the hashtag and token:

Output extract:

...Going through 302:Server:nginx/0.7.65Date:Mon,09Jan2012 20:20:11 GMTContent-Type:text/html;charset=utf-8Connection:closeCache-Control:privateLocation:https://stackexchange.com/oauth/login_success#access_token=K4zKd*HkKw5Opx(a8t12FA))&expires=86400Content-Length:218...

More on catching redirects with urllib2 on StackOverflow (of course).

Post a Comment for "How To Programmatically Retrieve Access_token From Client-side Oauth Flow Using Python?"