I followed this Laravel token API tutorial: http://rjv.im/post/95988160186/api-token-authentication-with-laravel-and-sentry-part. I have written the following cURL request to communicate with my API:
curl -H "X-Auth-Token:tokenhere" http://localhost:8000/account
The request works properly, and accurately returns the expected data. When I translate this to Python I receive urllib2.HTTPError: HTTP Error 401: Unauthorized
import urllib2
req = urllib2.Request('http://localhost:8000/account')
req.add_header("X-Auth-Token", "tokenhere")
resp = urllib2.urlopen(req)
content = resp.read()
print content
If I pass user credentials using basic auth instead of an X-Auth-Token, the request works as expected:
import urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://localhost:8000/account", headers = { "Authorization": basic_authorization("usernameHere", "passwordHere"), })
f = urllib2.urlopen(req)
print f.read()
Any assistance would be much appreciated.
X-Auth-Tokenheader on the server side? Because normally, headers are sent with a space after the colon—that's howcurlis going to send all the rest of your headers, and howurllib2is going to send all of the headers, including the one you added. If your server is actually expecting'X-Auth-Token:tokenhere'and rejecting'X-Auth-Token: tokenhere', that's a bug that you need to fix on the server side.nc -kl 8000instead of your server, and watch what it prints out when yourcurlcommand and Python program try to talk to it?curlcommand work even right after the Python script failed, or did it just work in the past?