Search code examples
asp.netpython-3.xbasic-authentication

Basic HTTP Authentication with python 3.2 (urllib.request)


This is my first post with this account, and Ive been struggling for the last week to get this to work, so I hope someone can help me get this working.

Im trying to pull some data from https://api.connect2field.com/ but its rejecting all of my authentication attempts from python (not from a browser though). The code Im using

import urllib.request as url
import urllib.error as urlerror
urlp = 'https://api.connect2field.com/api/Login.aspx'

# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = url.HTTPBasicAuthHandler()
auth_handler.add_password(realm='Connect2Field API',
                          uri=urlp,
                          user='*****',
                          passwd='*****')
opener = url.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
url.install_opener(opener)
try:
    f = url.urlopen(urlp)
    print (f.read())
except urlerror.HTTPError as e:
        if hasattr(e, 'code'):
            if e.code != 401:
                print ('We got another error')
                print (e.code)
        else:
            print (e.headers)

Im pretty sure the code is doing everything right, which makes me think that maybe theres another authentication step that ASP.net requires. Does anybody have any experience with ASP.Net's authentication protocol?

Im gonna be checking this post throughout the day, so I can post more info if required.

Edit: Ive also tried running my script against a basic http auth server running at home, and it authenticates, so Im pretty sure the request is set up properly.


Solution

  • It appears that IIS is set up to do basic authentication, ASP.NET will be most probably be configured to use windows authentication.

    As you have said that authentication works via browser, so the best bet for you is to use tool such as fiddler to capture request/response when connecting via browser and also when connecting via your code. Compare them to troubleshoot the issue.

    For example, I remember a case where the web site first requested authentication credentials and then re-directed to different url which prompted for different credentials.