all. I am working on a django / mod_wsgi / apache2 site that serves sensitive information using https for all requests and responses. All views are recorded for redirection if the user is not authenticated. It also has several views designed to function as a RESTful web service.
I am currently writing a script that uses urllib / urllib2 to contact several of these services to download a series of very large files. I am having problems with 403: FORBIDDEN errors when trying to login.
The method (draft) that I use for authentication and login:
def login( base_address, username=None, password=None ):
if username == None:
username = raw_input( 'Username: ' )
if password == None:
password = getpass.getpass( 'Password: ' )
log.info( 'Logging in %s' % username )
cookieHandler = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener( urllib2.HTTPSHandler(), cookieHandler )
urllib2.install_opener( opener )
login_url = base_address + PATH_TO_LOGIN
log.debug( "login_url: " + login_url )
login_page = opener.open( login_url )
csrf_cookie = None
for cookie in cookieHandler.cookiejar:
if cookie.name == 'csrftoken':
csrf_cookie = cookie
break
if not cookie:
raise IOError( "No csrf cookie found" )
log.debug( "found csrf cookie: " + str( csrf_cookie ) )
log.debug( "csrf_token = %s" % csrf_cookie.value )
login_data = urllib.urlencode( dict(
username=username, password=password,
csrfmiddlewaretoken=csrf_cookie.value ) )
log.debug( "login_data: %s" % login_data )
req = urllib2.Request( login_url, login_data )
response = urllib2.urlopen( req )
log.debug( 'response url:\n' + str( response.geturl() ) + '\n' )
log.debug( 'response info:\n' + str( response.info() ) + '\n' )
if response.geturl() == login_url:
raise IOError( 'Authentication refused' )
log.info( '\t%s is logged in' % username )
return opener
HTTPCookieHandler cookie Django script, - .
, CSRFmiddleware Django , csrf , / load cookiejar. , http/ .
, 403 / https-. , http-.
Apache ( ). script , , - Apache ( ).
python, , SSL.
, urllib2 https . -, , script - . ?
, , cookie , , .
.