OAuth User Information Fetching with Authlib

  • Share this:

Code introduction


This function uses the OAuth component from the Authlib library to register a third-party authentication provider and fetch user information.


Technology Stack : Authlib, Flask, OAuth, Requests

Code Type : The type of code

Code Difficulty :


                
                    
def get_random_user(user_id):
    from authlib.integrations.flask_client import OAuth
    from authlib.integrations.requests_client import RequestsClient

    # Initialize OAuth with Flask application
    oauth = OAuth()
    oauth.register(
        name='example_provider',
        client_id='your-client-id',
        client_secret='your-client-secret',
        access_token_url='https://example.com/oauth/token',
        access_token_params=None,
        authorize_url='https://example.com/oauth/authorize',
        authorize_params=None,
        api_base_url='https://example.com/api',
        client_kwargs={'scope': 'profile email'},
        requests_session=RequestsClient()
    )

    # Fetch user profile using the OAuth client
    user = oauth.client.get(f'https://example.com/api/users/{user_id}')
    user_data = user.json()

    return user_data