Rest API authentication process in Python

Introduction to REST API


REST stands for Representational state transfer and REST API's are the type of API's that will enable you to use standard HTTP methods (GET, PUT, POST, DELETE, etc.) to manipulate the data in quick time. The client sends a request along with the resource in the form of REST API and the server will return the state of the resource along with request data back to the client.

Each request from the client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. The session state is therefore kept entirely on the client. All in all, it's a stateless transition i.e. after every request is executed, the entire session will be terminated/closed and a new state/session will be formed for a new request.

While requesting data from the server, it is required to pass the resource as an argument to the request. Similarly, it is required to send the data in the request if that is required to be updated on the server-side.

During this process, communication is needed to be established between the client and the server. Authentication is an integral part of any communication system. The person executing API request needs to be authenticated in the system


Authentication Methods


There are various authentication methods available but Basic Authentication and bearer token based authentications are the popular methods that are widely used.


Basic Authentication.
       
In the basic authentication method/process, authentication happens based on credentials like username 
and password.
         
Requests module in Python provides all the necessary classes and methods to execute API. 
auth class from the requests module has HTTPBasicAuth in-built method using which authentication can be done for a particular user.

import requests
from requests.auth import HTTPBasicAuth
import json
from basicauth import encode
from datetime import datetime
class Authentication():
    def __init__(self, url, auth=[], token=''):
        self.url = url
        self.auth = auth
        self.token = token
    def basic_auth(self):
        """
        [Documentation]
        This method will authenticate the user based on the username and password values
        passed to the Authenticate class.
        :return: Nothing
        """
        now = datetime.now()
        headers = {
            'Date': str(now.strftime("%Y-%m-%d %H:%M:%S %p")),
            'Content-Type''application/json',
            'User-Agent''PostmanRuntime/7.22.0',
            'Connection''keep-alive'
        }
        if self.auth:
            authentication = HTTPBasicAuth(*self.auth)
        else:
            raise Exception ("Basic auth credentials are missing")
        response = requests.get(self.url, auth=authentication, headers=headers)
        if response.ok == True and response.json()['authenticated'] == True:
            print('Authentication is successful for user "{}"'.format(*self.auth))
            return (response.json(), self.url, headers)
        else:
            print('Authentication is failed for user "{}"'.format(*self.auth))
There is another way to achieve basic authentication and i.e. by passing encoded form of string of
username and password to the Authorization key in the header. Code snippent below depicts
how encoded string can be generated using encode class of basicauth module in Python to authenticate any user.

def basic_auth_encode(self):
    """
    [Documentation]
    This method will authenticate the user based on the username and password values
    supplied to the API.
    :return: Nothing
    """
    username, password = self.auth
    encoded_str = encode(username, password)
    print(encoded_str)
    now = datetime.now()
    headers = {
        'Date': str(now.strftime("%Y-%m-%d %H:%M:%S %p")),
        'Content-Type''application/json',
        'Authorization': encoded_str,
        'User-Agent''PostmanRuntime/7.22.0',
        'Connection''keep-alive'
    }
    response = requests.get(self.url, headers=headers)
    if response.ok == True and response.json()['authenticated'] == True:
        print('Authentication is successful for user "{}"'.format(self.auth))
        return (response.json(), self.url, headers, response.text.encode('utf8'))
    else:
        print('Authentication is failed for user "{}"'.format(self.auth))

Bearer token-based authentication

In the token-based authentication method/process, a token is generated by an API and this token is used later on to establish a communication between the client and the server. Token returned by the server in response will be passed in the other API requests as bearer token authentication methods.

_get_token API in the below code shows how token key can be collected from API request body from 'Authorization' key and how that can be passed in the headers in 'Authorization' key to execute other requests.

def _get_token(self, token_url=''):
    """

    [Documentation]

    This method will return a token in response.

    Optional Parameter:

        :param token_url:

    :return: token

    """
    payload = "{\"user_name\":\"user\",\"password\":\"root\",\"force_login\":true}"

    headers = {
        'Content-Type''application/json'
    }

    if self.url:

        url1 = self.url

    else:

        url1 = token_url

    print(url1)

    r = requests.post(url1, headers=headers, data=payload)

    print(r)

    token = r.headers.get('Authorization')

    return token

def bearer_token_auth(self, token='', token_url=''):

    """
    [Documentation]

    This method will authenticate the user by passing token value to the API

    Optional Parameters:

        :param token:

        :param token_url:

    :return:

    """
    if token:

        auth_token = token

    else:

        auth_token = self._get_token(token_url)

    if token_url:

        url = token_url

    else:

        url = self.url

    headers = {

        'Content-Type''application/json',

        'Authorization''Bearer {}'.format(auth_token)

    }
    response = requests.get(url, headers=headers)

    if response.ok == True and response.json()["authenticated"] == True:

        print('Authentication is successful with token "{}"'.format(auth_token))

        return (response.json(), self.url, headers, response.text.encode('utf8'))

    else:

        print('Authentication is failed with token "{}"'.format(auth_token))

Comments

Post a Comment