Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Securing Django Admin login with OTP (2 Factor Authentication)
Next article icon

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

Last Updated : 05 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


 


Next Article
Securing Django Admin login with OTP (2 Factor Authentication)
author
gupta_shrinath
Improve
Article Tags :
  • Python
  • HTML
  • Write From Home
  • Python-projects
  • Python Flask
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences