OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
Last Updated : 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.
What is OAuth?
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.
Terminologies in OAuth
- 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.
Steps involved to setup OAuth
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.
Installing required dependencies
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.
Retrieve the client credentials from the providers
- 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 the UI
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>
Creating the Flask app
Initialize the flask application
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.
Initialize OAuth
Python3 from flask import Flask, render_template from 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.
Create OAuth for Google
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, redirect from authlib.integrations.flask_client import OAuth import 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)
Create OAuth for Twitter
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, redirect from authlib.integrations.flask_client import OAuth import 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)
Create OAuth for Facebook
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, redirect from authlib.integrations.flask_client import OAuth import 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)
Run the app
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.
Similar Reads
How to Add Authentication to App with Flask-Login
We can implement authentication, login/logout functionality in flask app using Flask-Login. In this article, we'll explore how to add authentication to a Flask app using Flask-Login. To get started, install Flask, Flask-Login, Flask-SQLAlchemy and Werkzeug using this command: pip install flask flask
6 min read
Flask API Authentication with JSON Web Tokens
Authentication is the process of verifying the identity of the user. It checks whether the user is real or not. It is used to provide access to resources only to valid users. There are two types of Authentication: Single Factor Authentication: In this only one piece of information is needed to verif
7 min read
Python Django | Google authentication and Fetching mails from scratch
Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We'll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these
12 min read
Securing Django Admin login with OTP (2 Factor Authentication)
Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here â Building Blog CMS (Content
2 min read
Two-Factor Authentication using Google Authenticator in Python
Two Factor Authentication or 2FA is an advanced method of user authentication and a subset of multi-factor authentication mechanisms. 2FA enhances the security of its user accounts by adding another layer of authenticity challenge after traditional passwords are used in single-factor authentication.
3 min read
Server Side Google Authentication using FastAPI and ReactJS
FastAPI is a modern, fast, web framework for building APIs with Python, and react is a javascript library that can be used to develop single-page applications. So in this article, we are going to discuss the server-side authentication using FastAPI and Reactjs and we will also set the session. First
4 min read
Token Authentication in Django Channels and Websockets
Prerequisites: Django, WebSockets, Django channels, Token authentication The most popular Django topics right now are WebSockets and Django channels because they make it possible to communicate quickly and easily while working in real-time without constantly refreshing the page. When working with th
13 min read
Django Authentication Project with Firebase
Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to uploa
7 min read
Using JWT for user authentication in Flask
JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts: Header - Contains metadata (e.g., algorithm used for signing).Payl
7 min read
Access a Site with Two-Factor Authentication Using Python Requests
web security is of paramount importance, and many websites implement two-factor authentication (2FA) to enhance security. This additional layer of security ensures that even if someone obtains your password, they cannot access your account without the second form of verification, usually a code sent
4 min read