Search code examples
pythonpython-2.7urllib2

"Invalid security token" while using urllib2


I am trying to get the content of a http request using a python script. But I am receiving Invalid security token error while executing it. Here is the following snippet

#!/usr/bin/python
import urllib2

username="username"
password="password"
url='some_url'
def encodeUserData(user, password):
    return "Basic " + (user + ":" + password).encode("base64").rstrip()
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/json")
req.add_header('Authorization', encodeUserData(username, password))
# make the request and print the results
print res.read()

Username and password has special characters.


Solution

  • Given that you are able to successfully run the request with curl on bash, and get <Response [200]>, you should be able to run it in python-2.7 with both requests and urllib2. In fact, I just tried and the following works for me:

    # with requests
    import requests
    username="username"
    password="password"
    url='https://url.html'
    def encodeUserData(user, password):
        return "Basic " + (user + ":" + password).encode("base64").rstrip()
    
    response = requests.get(url, headers={'Authorization': encodeUserData(username, password)})
    print response.content
    

    If you want to use urllib2, this also works.

    # with urllib2
    import urllib2
    username="username"
    password="password"
    url='https://url.html'
    def encodeUserData(user, password):
        return "Basic " + (user + ":" + password).encode("base64").rstrip()
    
    req = urllib2.Request(url)
    req.add_header('Authorization', encodeUserData(username, password))
    res = urllib2.urlopen(req)
    print res.read()
    

    If this does not work, I would suggest you to substitute username and password with the encoded line directly, and see if that would work.