Creating OAuth2 Session for Access Token Acquisition

  • Share this:

Code introduction


This function creates an OAuth2Session to interact with an OAuth2 authorization server and obtain an access token.


Technology Stack : requests, oauthlib.oauth2, requests_oauthlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
import requests
from oauthlib.oauth2 import BackendApplicationClient
from oauthlib.oauth2 import TokenRequest
from requests_oauthlib import OAuth2Session

def create_oauth_session(client_id, client_secret, token_url):
    # Create a client with the provided client_id and client_secret
    client = BackendApplicationClient(client_id=client_id)
    
    # Create an OAuth2Session with the client
    oauth_session = OAuth2Session(client=client)
    
    # Create a token request
    token_request = TokenRequest(
        token_url=token_url,
        client_id=client_id,
        client_secret=client_secret,
        resource_owner_username=None,
        resource_owner_password=None,
        scopes=None
    )
    
    # Exchange the token request for a token
    token = oauth_session.fetch_token(token_url, token_request)
    
    return oauth_session