1

I want to obtain authentication token using urllib2 in python. My program is (I changed credentials):

import urllib2
import urllib

USER_NAME = 'me'
USER_PASSWORD = 'mypass'

url = "http://myurl.org/oauth/token"

query_args = { "grant_type":"password",
               "username":USER_NAME,
               "password":USER_PASSWORD,
               "client_secret":'123',
                'client_id':'456'}

encoded_args = urllib.urlencode(query_args)
print urllib2.urlopen(url, data=encoded_args).read()

The result of running is 403 Error: Forbidden. However I can obtain the authentication token using curl in terminal:

curl -X POST "url" -d "credentials"

I used "url" and "credentials" from the python code (to obtain "credentials" string I prinded out encoded_args).

How to get authentication token using urllib2?

2
  • use try-except to log the full error response. maybe it's useful... Commented Nov 23, 2013 at 9:26
  • and you are really using HTTPS, right? Commented Nov 23, 2013 at 9:32

1 Answer 1

1

First off, you shouldn't mix urllib and urllib2 in the same application. urllib2 is the successor to urllib, and will do the same things.

The real answer here is to use an OAuth capable library to like python-oauth2 to do the heavy lifting for you. Or better, switch from urllib2 to a slightly higher level package like requests, and use one of their brilliant oauth plugins for a single solution which kicks some ass!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.