OAuth1 Access Token Retrieval using OAuthlib

  • Share this:

Code introduction


This function uses the OAuthlib library to retrieve an access token by exchanging an authorization code obtained from OAuth 1.0. The function accepts client ID, client secret, token URL, and authorization response, then parses the authorization response, and uses an OAuth1 client with HMAC signature method to request the access token.


Technology Stack : OAuthlib, OAuth1, SignatureMethod_HMAC, urlparse, parse_qs

Code Type : OAuth 1.0 Access Token Retrieval

Code Difficulty : Intermediate


                
                    
def get_access_token(client_id, client_secret, token_url, authorization_response):
    from oauthlib.oauth1 import OAuth1
    from oauthlib.oauth1 import SignatureMethod_HMAC
    from urllib.parse import urlparse, parse_qs

    # Create an OAuth1 client
    client = OAuth1(client_id, client_secret, signature_method=SignatureMethod_HMAC())

    # Parse the authorization response
    query_params = parse_qs(urlparse(authorization_response).query)
    token_response = client.parse_authorization_response(authorization_response)

    # Exchange the authorization code for an access token
    token_response = client.authorize_token_request(token_url, body=token_response)

    return token_response