OAuth Authentication with Flask – Connect to Google, Twitter, and Facebook

05 Oct, 2021
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure.
OAuth stands for Open Authorization and was implemented to achieve a connection between online services. The OAuth Community Site defines it as “An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.”. A popular example of OAuth would be the Sign in with Google button present on various websites. Here the website service connects with the google service to provide you with an easy option to authorize your resource to the desired service. There are two versions of OAuth OAuth1.0 and OAuth2.0 now.
Client: It is the application or service trying to connect to the other service.
Provider: It is the service to which the client connects.
Authorization URL: It is the URL provided by the provider to which the client sends requests.
Client ID and Secret:  It is provided by the provider and used when the authorization request is sent to the provider by the client.
Authorization Code: It is a code that is retrieved by the client on successful authentication by the user and it is sent to the provider’s authorization server.
Callback URL: It is the URL set by the client to which the provider sends the authorization code and the user resources are retrieved by the client service.
Step 1: Register your application as a client on the provider website. You will receive the client credentials which include the client ID and client secret.
Step 2: The client application sends an authorization request to the provider’s authorization URL.
Step 3: The user authenticates themselves on the provider’s site and allows resources to be used by the client service.
Step 4: The provider sents the authorization code to the client
Step 5: The client sends the authorization code to the provider’s authorization server.
Step 6: The provider sends the client tokens which can be used for accessing user resources.
Now that the concept of OAuth is clear we can start building our application. There are various libraries available to us that can be used to achieve OAuth. The library we will be using is AuthLib which supports OAuth 1.0 and OAuth 2.0.
To install the required dependencies type the below command in the terminal.
pip install -U Flask Authlib requests
Note: It is recommended to create a virtual environment before installing these dependencies.
Google: Create your Google OAuth Client at https://console.cloud.google.com/apis/credentials, make sure to add http://localhost:5000/google/auth/ into Authorized redirect URIs.
Twitter: Create your Twitter Oauth 1.0 Client at https://developer.twitter.com/ by creating an app. Add http://localhost:5000/twitter/auth/ into Authorized redirect URIs.
Facebook: Create your Facebook OAuth Client at https://developer.facebook.com/, by creating an app. Add http://localhost:5000/facebook/auth/ into Authorized redirect URIs.
The client credentials can be used directly in the program but in actual production, these credentials are to be stored in environment variables.
Create a folder called templates and inside create an index.html file. Paste the following code inside the index.html file. It is a simple code that creates buttons for every provider.
HTML
<!DOCTYPE html><html lang="en">   <head>      <meta charset="UTF-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <title>Authlib Connect</title>   </head>   <body>      <p align="center">         <a href="google/">         <img id="google"            src="https://img.shields.io/badge/Google-Connect-brightgreen?style=for-the-badge&labelColor=black&logo=google"            alt="Google"> <br>         </a>         <a href="twitter/">         <img id="twitter"            src="https://img.shields.io/badge/Twitter-Connect-brightgreen?style=for-the-badge&labelColor=black&logo=twitter"            alt="Twitter"> <br>         </a>         <a href="facebook/">         <img id="facebook"            src="https://img.shields.io/badge/Facebook-Connect-brightgreen?style=for-the-badge&labelColor=black&logo=facebook"            alt="Facebook"> <br>         </a>      </p>      </body></html>
Let’s create a simple flask application that will do nothing and will simply render the above-created HTML file onto the home page.
Python3
from flask import Flask, render_template  app = Flask(__name__) app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<\!\xd5\xa2\xa0\x9fR"\xa1\xa8' '''    Set SERVER_NAME to localhost as twitter callback    url does not accept 127.0.0.1    Tip : set callback origin(site) for facebook and twitter    as http://domain.com (or use your domain name) as this provider    don't accept 127.0.0.1 / localhost''' app.config['SERVER_NAME'] = 'localhost:5000' @app.route('/')def index():    return render_template('index.html') if __name__ == "__main__":    app.run(debug=True)
Run the server using the following command to make sure that the application is running successfully and the index.html page is displayed. 
After creating the apps let’s see how to add the Oauth for google, Twitter, and Facebook. But at first let’s initialize the OAuth.
Python3
from flask import Flask, render_templatefrom authlib.integrations.flask_client import OAuth app = Flask(__name__) app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!/\xd5\xa2\xa0\x9fR"\xa1\xa8''''    Set SERVER_NAME to localhost as twitter callback    url does not accept 127.0.0.1    Tip : set callback origin(site) for facebook and twitter    as http://domain.com (or use your domain name) as this provider    don't accept 127.0.0.1 / localhost''' app.config['SERVER_NAME'] = 'localhost:5000'oauth = OAuth(app) @app.route('/')def index():    return render_template('index.html') if __name__ == "__main__":    app.run(debug=True)
Here we have initialized the OAuth using the OAuth(app) class and we have changed our server name to localhost:5000. Now let’s see how to create the OAuth for different Platforms.
Python3
# The user details get print in the console.# so you can do whatever you want to do instead# of printing it from flask import Flask, render_template, url_for, redirectfrom authlib.integrations.flask_client import OAuthimport os app = Flask(__name__)app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!/xd5\xa2\xa0\x9fR"\xa1\xa8' '''    Set SERVER_NAME to localhost as twitter callback    url does not accept 127.0.0.1    Tip : set callback origin(site) for facebook and twitter    as http://domain.com (or use your domain name) as this provider    don't accept 127.0.0.1 / localhost''' app.config['SERVER_NAME'] = 'localhost:5000'oauth = OAuth(app) @app.route('/')def index():    return render_template('index.html') @app.route('/google/')def google():       # Google Oauth Config    # Get client_id and client_secret from environment variables    # For developement purpose you can directly put it    # here inside double quotes    GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')    GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')         CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'    oauth.register(        name='google',        client_id=GOOGLE_CLIENT_ID,        client_secret=GOOGLE_CLIENT_SECRET,        server_metadata_url=CONF_URL,        client_kwargs={            'scope': 'openid email profile'        }    )         # Redirect to google_auth function    redirect_uri = url_for('google_auth', _external=True)    return oauth.google.authorize_redirect(redirect_uri) @app.route('/google/auth/')def google_auth():    token = oauth.google.authorize_access_token()    user = oauth.google.parse_id_token(token)    print(" Google User ", user)    return redirect('/') if __name__ == "__main__":    app.run(debug=True)
Python3
# The user details get print in the console.# so you can do whatever you want to do instead# of printing it from flask import Flask, render_template, url_for, redirectfrom authlib.integrations.flask_client import OAuthimport os app = Flask(__name__)app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O/<!\xd5\xa2\xa0\x9fR"\xa1\xa8' '''    Set SERVER_NAME to localhost as twitter callback    url does not accept 127.0.0.1    Tip : set callback origin(site) for facebook and twitter    as http://domain.com (or use your domain name) as this provider    don't accept 127.0.0.1 / localhost''' app.config['SERVER_NAME'] = 'localhost:5000'oauth = OAuth(app) @app.route('/')def index():    return render_template('index.html') @app.route('/google/')def google():       # Google Oauth Config    # Get client_id and client_secret from environment variables    # For developement purpose you can directly put it here inside double quotes    GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')    GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')    CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'    oauth.register(        name='google',        client_id=GOOGLE_CLIENT_ID,        client_secret=GOOGLE_CLIENT_SECRET,        server_metadata_url=CONF_URL,        client_kwargs={            'scope': 'openid email profile'        }    )         # Redirect to google_auth function    redirect_uri = url_for('google_auth', _external=True)    return oauth.google.authorize_redirect(redirect_uri) @app.route('/google/auth/')def google_auth():    token = oauth.google.authorize_access_token()    user = oauth.google.parse_id_token(token)    print(" Google User ", user)    return redirect('/') @app.route('/twitter/')def twitter():       # Twitter Oauth Config    TWITTER_CLIENT_ID = os.environ.get('TWITTER_CLIENT_ID')    TWITTER_CLIENT_SECRET = os.environ.get('TWITTER_CLIENT_SECRET')    oauth.register(        name='twitter',        client_id=TWITTER_CLIENT_ID,        client_secret=TWITTER_CLIENT_SECRET,        request_token_url='https://api.twitter.com/oauth/request_token',        request_token_params=None,        access_token_url='https://api.twitter.com/oauth/access_token',        access_token_params=None,        authorize_url='https://api.twitter.com/oauth/authenticate',        authorize_params=None,        api_base_url='https://api.twitter.com/1.1/',        client_kwargs=None,    )    redirect_uri = url_for('twitter_auth', _external=True)    return oauth.twitter.authorize_redirect(redirect_uri) @app.route('/twitter/auth/')def twitter_auth():    token = oauth.twitter.authorize_access_token()    resp = oauth.twitter.get('account/verify_credentials.json')    profile = resp.json()    print(" Twitter User", profile)    return redirect('/') if __name__ == "__main__":    app.run(debug=True)
Python3
# The user details get print in the console.# so you can do whatever you want to do instead# of printing it from flask import Flask, render_template, url_for, redirectfrom authlib.integrations.flask_client import OAuthimport os app = Flask(__name__)app.secret_key = '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O/<!\xd5\xa2\xa0\x9fR"\xa1\xa8' '''    Set SERVER_NAME to localhost as twitter callback    url does not accept 127.0.0.1    Tip : set callback origin(site) for facebook and twitter    as http://domain.com (or use your domain name) as this provider    don't accept 127.0.0.1 / localhost''' app.config['SERVER_NAME'] = 'localhost:5000'oauth = OAuth(app) @app.route('/')def index():    return render_template('index.html') @app.route('/google/')def google():       # Google Oauth Config    # Get client_id and client_secret from environment variables    # For developement purpose you can directly put it here inside double quotes    GOOGLE_CLIENT_ID = os.environ.get('GOOGLE_CLIENT_ID')    GOOGLE_CLIENT_SECRET = os.environ.get('GOOGLE_CLIENT_SECRET')    CONF_URL = 'https://accounts.google.com/.well-known/openid-configuration'    oauth.register(        name='google',        client_id=GOOGLE_CLIENT_ID,        client_secret=GOOGLE_CLIENT_SECRET,        server_metadata_url=CONF_URL,        client_kwargs={            'scope': 'openid email profile'        }    )         # Redirect to google_auth function    redirect_uri = url_for('google_auth', _external=True)    return oauth.google.authorize_redirect(redirect_uri) @app.route('/google/auth/')def google_auth():    token = oauth.google.authorize_access_token()    user = oauth.google.parse_id_token(token)    print(" Google User ", user)    return redirect('/') @app.route('/twitter/')def twitter():       # Twitter Oauth Config    TWITTER_CLIENT_ID = os.environ.get('TWITTER_CLIENT_ID')    TWITTER_CLIENT_SECRET = os.environ.get('TWITTER_CLIENT_SECRET')    oauth.register(        name='twitter',        client_id=TWITTER_CLIENT_ID,        client_secret=TWITTER_CLIENT_SECRET,        request_token_url='https://api.twitter.com/oauth/request_token',        request_token_params=None,        access_token_url='https://api.twitter.com/oauth/access_token',        access_token_params=None,        authorize_url='https://api.twitter.com/oauth/authenticate',        authorize_params=None,        api_base_url='https://api.twitter.com/1.1/',        client_kwargs=None,    )    redirect_uri = url_for('twitter_auth', _external=True)    return oauth.twitter.authorize_redirect(redirect_uri) @app.route('/twitter/auth/')def twitter_auth():    token = oauth.twitter.authorize_access_token()    resp = oauth.twitter.get('account/verify_credentials.json')    profile = resp.json()    print(" Twitter User", profile)    return redirect('/') @app.route('/facebook/')def facebook():       # Facebook Oauth Config    FACEBOOK_CLIENT_ID = os.environ.get('FACEBOOK_CLIENT_ID')    FACEBOOK_CLIENT_SECRET = os.environ.get('FACEBOOK_CLIENT_SECRET')    oauth.register(        name='facebook',        client_id=FACEBOOK_CLIENT_ID,        client_secret=FACEBOOK_CLIENT_SECRET,        access_token_url='https://graph.facebook.com/oauth/access_token',        access_token_params=None,        authorize_url='https://www.facebook.com/dialog/oauth',        authorize_params=None,        api_base_url='https://graph.facebook.com/',        client_kwargs={'scope': 'email'},    )    redirect_uri = url_for('facebook_auth', _external=True)    return oauth.facebook.authorize_redirect(redirect_uri) @app.route('/facebook/auth/')def facebook_auth():    token = oauth.facebook.authorize_access_token()    resp = oauth.facebook.get(        'https://graph.facebook.com/me?fields=id,name,email,picture{url}')    profile = resp.json()    print("Facebook User ", profile)    return redirect('/') if __name__ == "__main__":    app.run(debug=True)
Start server with: 
python app.py
Then visit: 
http://localhost:5000/
Note: The OAuth configuration for every provider is different and depends on the version of OAuth. Every provider has its own documentation on implementing the protocol so make sure to check it out.
 
sagartomar9927
ruhelaa48
Python Flask
Python-projects
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function