SoFunction
Updated on 2025-04-11

Common ways to handle HTTP authentication in Python

introduction

In Python, HTTP authentication usually refers to the need to provide some form of authentication information (such as username and password) when sending a request to the server so that the server can verify the client's identity. This authentication mechanism is usually used in scenarios where resources need to be protected, such as API interfaces.

Handling HTTP authentication usually involves using the requests library. The requests library provides an easy way to handle HTTP requests that require authentication. Here are some common ways to handle HTTP authentication:

1. Basic Authentication

Basic authentication is the easiest way to authenticate, which is achieved by adding an Authorization field to the header of an HTTP request.

Writing method 1:

import requests
from  import HTTPBasicAuth
 
url = '/api/data'
username = 'your_username'
password = 'your_password'
 
response = (url, auth=HTTPBasicAuth(your_username, your_password))
print()

Writing method 2:

import requests
 
url = '/protected'
username = 'your_username'
password = 'your_password'
 
# Base64 encoding of username and password, put into the request headerauth_string=f'{your_username}:{your_password}'
b64_auth_string = base64.b64encode(auth_string.encode()).decode()
header={'Authorization': 'Basic ' + b64_auth_string}
 
# Use the headers parameter of requestsresponse = (url, headers=header)
 
print()

2. Digest Authentication

Abstract authentication is safer than basic authentication because it does not transmit passwords over the network plaintext.

import requests
from  import HTTPDigestAuth
 
url = '/protected'
username = 'your_username'
password = 'your_password'
 
# Use HTTPDigestAuthresponse = (url, auth=HTTPDigestAuth(username, password))
 
print()

3. Token Authentication

For authentication methods that require an API key or token, the token is usually sent as part of the request. This can be done by adding a specific field in the request header.

import requests
 
url = '/protected'
token = 'your_token_here'
 
headers = {
    'Authorization': f'Bearer {token}'  # Or use other authentication mechanisms, such as 'Token {token}', etc.}
 
response = (url, headers=headers)
 
print()

4. OAuth 2.0 certification

For OAuth 2.0 authentication, you can userequests-oauthliblibrary to simplify the process. First, you need to install this library:

pip install requests-oauthlib

Then, you can use the following method to perform OAuth 2.0 authentication:

from requests_oauthlib import OAuth2Session
 
client_id = 'your_client_id'
client_secret = 'your_client_secret'
redirect_uri = 'your_redirect_uri'
authorization_base_url = '/oauth/authorize'
token_url = '/oauth/token'
 
oauth = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth.authorization_url(authorization_base_url)
# Here, you can open authorization_url to let the user log in and authorize your application.  After that, you will get an authorization code (code).# Use the authorization code to obtain the token:token = oauth.fetch_token(token_url, code='your_authorization_code')
# Now, you can use this token to make API calls:response = ('/protected')
print()

Summarize:

Which authentication method to choose depends on the specific scenario requirements and the requirements of the backend API. Basic authentication and digest authentication are natively supported by HTTP, while token and OAuth 2.0 authentication are often used in more complex scenarios such as API calls. For tokens and OAuth 2.0, additional libraries are needed to help manage the authentication process.

The above is the detailed content of common methods for Python to handle HTTP authentication. For more information about Python to handle HTTP authentication, please follow my other related articles!