python requests oauth2 example

Python Requests OAuth2 Example

OAuth2 is a commonly used authorization framework that allows a user to grant a third-party application access to their resources, such as their personal data or files, without sharing their login credentials. Python Requests is a popular HTTP library that enables developers to send HTTP requests using Python.

Here's an example of how to use Python Requests to authenticate with an OAuth2 server and access protected resources.

Step 1: Install Necessary Libraries

Before we can start making requests, we need to install the necessary libraries. You can install them using pip:


    pip install requests requests_oauthlib
    

Step 2: Get Authorization

The first step in using OAuth2 is to get authorization. This involves directing the user to the authorization server, where they will grant permission for the application to access their resources. In this example, we'll use the GitHub API as our authorization server.


    import requests_oauthlib
    
    # Create a session
    session = requests_oauthlib.OAuth2Session(
        client_id='your_client_id',
        redirect_uri='your_redirect_uri',
        scope=['repo', 'user'],
    )
    
    # Redirect user to GitHub for authorization
    authorization_url, state = session.authorization_url('https://github.com/login/oauth/authorize')
    print('Please go here and authorize:', authorization_url)
    
    # Get access token
    token_url = 'https://github.com/login/oauth/access_token'
    redirect_response = input('Paste the full redirect URL here:')
    token = session.fetch_token(token_url, authorization_response=redirect_response, client_secret='your_client_secret')
    

In the code above, we create a new OAuth2 session using the client ID, redirect URI, and desired scope. We then redirect the user to the authorization URL and prompt them to authorize the application. After authorization, the user will be redirected back to our redirect URI with a code that we can exchange for an access token. We use the fetch_token method to exchange the code for an access token.

Step 3: Access Protected Resources

Now that we have an access token, we can use it to access protected resources. In this example, we'll use the GitHub API to retrieve information about the authenticated user.


    # Use the access token to access protected resources
    response = session.get('https://api.github.com/user')
    
    # Print response
    print(response.content)
    

In the code above, we use the access token to make a GET request to the GitHub API's /user endpoint. We then print out the response content.

Alternative Approach: Using OAuth2Client

Another way to use OAuth2 with Python Requests is to use the OAuth2Client library. Here's an example:


    from requests_oauthlib import OAuth2Session
    from oauthlib.oauth2 import BackendApplicationClient
    
    client_id = 'your_client_id'
    client_secret = 'your_client_secret'
    
    # Create a session
    client = BackendApplicationClient(client_id=client_id)
    oauth = OAuth2Session(client=client)
    
    # Fetch access token
    token_url = 'https://example.com/oauth/token'
    token = oauth.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
    
    # Use access token to access protected resources
    headers = {'Authorization': 'Bearer ' + token['access_token']}
    response = requests.get('https://api.example.com/protected_endpoint', headers=headers)
    

In this example, we're using the BackendApplicationClient from the OAuth2 library to handle the authorization flow. We then use the fetch_token method to get an access token, and use that token in the Authorization header of our requests.