Python - HTTP Authentication


Advertisements

Authentication is the process of determining if the request has come from a valid user who has the required privileges to use the system. In the world of computer networking this is a very vital requirement as many systems keep interacting with each other and proper mechanism needs to ensure that only valid interactions happen between these programs.

The python module names requests has in-built feature to call various APIs provided by the serving web apps along with the user credentials. These credentials have to be embedded in the calling program. If the APIs verify it successfully then a valid login happens.

Installing Requests

We install the required python module named requests for running the authentication program.

pip install requests

Authenticating to Github

Below we see a simple authentication mechanism involving only the username and the password. A successful response indicates valid login.

import requests 
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print r

When we run the above program, we get the following output −


Authenticating to Twitter

We can also run a program to use twitter's api and make a successful login by using the following code. We use the OAuth1 method available in the requests module to process the parameters required by Twitter API. As we can see the requests module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism.

import requests
from requests_oauthlib import OAuth1

url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
              'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')

requests.get(url, auth=auth)

When we run the above program, we get the following output −

{
  "errors": [
    {
      "code": 215,
      "message": "Bad Authentication data."
    }
  ]
}

But using the proper values for OAuth1 parameters you get a successful response.

Useful Video Courses


Video

Python Online Training

Most Popular

187 Lectures 17.5 hours

Malhar Lathkar

Video

Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty

Video

Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official

Video

Python with Data Science

75 Lectures 13 hours

Eduonix Learning Solutions

Video

Python 3 from scratch to become a developer in demand

70 Lectures 8.5 hours

Lets Kode It

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

63 Lectures 6 hours

Abhilash Nelson

Advertisements