Search code examples
pythonhttpbasic-authentication

404 on HTTP-Basic authentication?


I have the following scenario:

  1. I have a ShoutCast-ish server which serves out radio station XML info.
  2. I have a Flash Player client which needs to fetch it.
  3. Flash Player can't fetch things over HTTP-Basic auth when using GET.
  4. So I'm building a Python CGI script to handle the authentication and re-serve the information.

Hope that makes sense. Essentially, my script serves as a proxy to the real data by creating an HTTP request, fetching the data, and serving it out when requested.

Here's my Python

#!/usr/bin/python
import base64, cgitb, sys, urllib2

cgitb.enable()

print "Content-Type: text/xml"
print

username = "username"
password = "password"
url = "http://s6.voscast.com:7158/admin.cgi?mode=viewxml"

auth = base64.encodestring('%s:%s' % (username, password))[:-1]
request = urllib2.Request(url)
request.add_header("Authorization", "Basic %s" % auth)

try:
    handle = urllib2.urlopen(request)
except IOError, e:
    print "Something Failed."
    sys.exit(1)

print handle.read()

Pretty straightforward, right? Unfortunately, it's not working. If I visit the website in a browser and enter the same username and password, it works; I can see the XML tree.

Instead, I get the following output in stdout:

Content-Type: text/xml

ICY 404 Resource Not Found
icy-notice1:<BR>SHOUTcast Distributed Network Audio Server/Linux v1.9.8<BR>
icy-notice2:The resource requested was not found<BR>

What am I doing wrong? Given the same URL, username, and password in a browser, everything works. What have I missed?


Solution

  • It may require a User-Agent or Accepts header as well.

    Try comparing/copying some of the http headers sent by your browser using Firebug or LiveHTTP Headers in Firefox, or Chrome dev tools. Compare your hexed password to confirm it is correct. Then add other headers one at a time until you've discovered the issue.