abualameer94
abualameer94

Reputation: 91

python basic authentication check

I'm trying to make script that check for the web page if it requires a basic http authentication or not before executing the needed command .

I'm sorry but i don't understand the libraries and the commands related to this check at python , I tried to search for it but failed to find any useful info .

For example I need the script to check the page www.google.com if it is gonna ask for credentials to view the page or not then complete the command.

Upvotes: 0

Views: 2551

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

If a server expects the client to use basic authentication, it'll respond to a request without such authentication with a WWW-Authenticate header, containing the word 'Basic'. See the Basic Authentication Scheme section of the HTTP RFC.

Using the standard Python libraries, you can test for that with:

from urllib2 import urlopen, HTTPError

try:
    response = urlopen(url)
except HTTPError as exc:
    # A 401 unauthorized will raise an exception
    response = exc
auth = response.info().getheader('WWW-Authenticate')
if auth and auth.lower().startswith('basic'):
    print "Requesting {} requires basic authentication".format(url)

Demo:

>>> from urllib2 import urlopen, HTTPError
>>> url = 'http://httpbin.org/basic-auth/user/passwd'
>>> try:
...     response = urlopen(url)
... except HTTPError as exc:
...     # A 401 unauthorized will raise an exception
...     response = exc
... 
>>> auth = response.info().getheader('WWW-Authenticate')
>>> if auth and auth.lower().startswith('basic'):
...     print "Requesting {} requires basic authentication".format(url)
... 
Requesting http://httpbin.org/basic-auth/user/passwd requires basic authentication

To add a timeout to the request as well, use:

from urllib2 import urlopen, HTTPError
import socket


response = None

try:
    response = urlopen(url, timeout=15)
except HTTPError as exc:
    # A 401 unauthorized will raise an exception
    response = exc
except socket.timeout:
    print "Request timed out"

auth = response and response.info().getheader('WWW-Authenticate')
if auth and auth.lower().startswith('basic'):
    print "Requesting {} requires basic authentication".format(url)

Upvotes: 3

Related Questions