Integrating Google OAuth2.0 in Flask with Authlib for User Login

  • Share this:

Code introduction


This function uses the Authlib library to integrate OAuth client into a Flask application, implementing user login through the Google OAuth2.0 protocol and fetching user information.


Technology Stack : Authlib, Flask, OAuth2.0, Google

Code Type : The type of code

Code Difficulty :


                
                    
def random_user_login(username, password):
    from authlib.integrations.flask_client import OAuth
    from authlib.integrations.base import IntegrationError

    # Initialize OAuth with a hypothetical Flask app
    oauth = OAuth()
    try:
        # Register a hypothetical provider, such as Google
        oauth.register(
            name='google',
            client_id='your-client-id',
            client_secret='your-client-secret',
            access_token_url='https://oauth2.example.com/token',
            authorization_url='https://oauth2.example.com/authorize',
            resource_owner_map={'email': 'email'}
        )

        # Fetch user info from Google using the OAuth client
        token = oauth.google.token(token={})
        user_info = oauth.google.user_info(token=token)
        return user_info
    except IntegrationError as e:
        return {'error': str(e)}