Chapter 3. Authenticating with Requests

Requests supports diverse kinds of authentication procedures, and it is built in such a way that the method of authentication feels like a cakewalk. In this chapter, we opt to throw light on various types of authentication procedures that are used by various tech giants for accessing the web resources.

We will cover the following topics:

  • Basic authentication
  • Digest authentication
  • Kerberos authentication
  • OAuth authentication
  • Custom authentication

Basic authentication

Basic authentication is a popular, industry-standard scheme of authentication, which is specified in HTTP 1.0. This method makes use of a user-ID and password submitted by the user to get authenticated. The submitted user-ID and password are encoded using Base64 encoding standards and transmitted across HTTP. The server gives access to the user only if the user-ID and the password are valid. The following are the advantages of using basic authentication:

  • The main advantage of using this scheme is that it is supported by most of the web browsers and servers. Even though it is simple and straightforward, it does have some disadvantages. Though all the credentials are encoded and transferred in the requests, they are not encrypted which makes the process insecure. One way to overcome this problem is by using SSL support while initiating a secure session.
  • Secondly, the credentials persist on the server until the end of the browser session, which may lead to the seizure of the resources. And also, this authentication process is wide open to Cross Site Request Forgery (CSRF) attacks, as the browser automatically sends the credentials of the user in the subsequent requests.

The basic authentication flow contains two steps:

  1. If a requested resource needs authentication, the server returns http 401 response containing a WWW-Authenticate header.
  2. If the user sends another request with the user ID and password in the Authorization header, the server processes the submitted credentials and gives the access.

You can see this in the following diagram:

Basic authentication

Using basic authentication with Requests

We can use the requests module to send a request to undergo basic authentication very easily. The process can be seen as follows:

>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://demo.example.com/resource/path', auth=HTTPBasicAuth('user-ID', 'password'))

In the preceding lines of code, we performed basic authentication by creating an HTTPBasicAuth object; then we passed it to the auth parameter, which will be submitted to the server. If the submitted credentials gets authenticated successfully, the server returns a 200 (Successful) response, otherwise, it will return a 401 (Unauthorized) response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.51.145