Table of contents
1.
Introduction
2.
Features of Flask OAuth
3.
Terminologies in OAuth
4.
OAuth Authentication in Flask – Connect to Google, Instagram, and Facebook
4.1.
Steps to setup OAuth
4.2.
Necessary Installations
4.3.
Getting the Credentials for Client from Providers
4.4.
Creating the UI
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

User Authentication OAuth in Flask

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

OAuth stands for Open Authorization, and it is implemented to achieve a connection between online services. As per the official community site, it is an open protocol to allow secure authorization in a simple and standard method from web, mobile, and desktop applications. 

The most common example of OAuth is the Sign in with Google button present on so many websites. The website service connects with the google service to provide us with a convenient option to authorize our resources to the service we want. 

Let us help you learn about the integration of OAuth in Flask for the authentication of the user using Google, Instagram, and Facebook in our Flask application.

Features of Flask OAuth

OAuth in Flask has the following features:

  • Support for OAuth 1.0a
  • It has a friendly API
  • It directly integrates with Flask.
  • It provides support for remote method invocation to the restful APIs.

Terminologies in OAuth

Some of the usual terminologies used in OAuth in Flask are: 

  • Client: The person or the application trying to connect to the other service.
  • Provider: The service to which the client connects.
  • Authorization URL: The URL provided by the provider to which the client sends requests.
  • Client ID and Secret:  When the client sends the authorization request to the provider, this is the unique ID supplied by the provider.
  • Authorization Code: It's a code that the client gets once the user is successfully authenticated and delivered to the provider's authorization server.
  • Callback URL: The URL is set by the client to which the provider sends the authorization code.

OAuth Authentication in Flask – Connect to Google, Instagram, and Facebook

Here, we will build a Flask application that will use the OAuth protocol to fetch user information. 

Steps to setup OAuth

Following are the steps to set up OAuth:

Step 1: Firstly, we need to register our application as a client on the website to provide us with the information. After that, we will receive the client credentials, including the client ID and client secret.

Step 2: Now, we will receive an authorization request to the provider's authorization URL from the client application.

Step 3: Afterward, the user needs to authenticate themselves on the provider's site, and all the necessary rights need to be granted.

Step 4: The provider will send the authorization code to the client

Step 5: The client will send the authorization code to the provider's authorization server.

Step 6: At the end, the provider will send the client tokens that can be used to access user resources.

Necessary Installations

To get the required dependencies, type the below command in the terminal.

pip install -U Flask Authlib request

Getting the Credentials for Client from Providers

  • Google: Add http://localhost:5000/google/auth/ to Authorized redirect URIs after creating our Google OAuth Client https://console.cloud.google.com/apis/credentials.
  • Instagram: Create your Instagram Oauth 1.0 Client at https://developer.instagram.com/ by creating an app. Add http://localhost:5000/instagram/auth/ into Authorized redirect URIs.
  • Facebook: Create an app at https://developer.facebook.com/ to start your Facebook OAuth Client. Authorized redirect URIs should include http://localhost:5000/facebook/auth.

Creating the UI

Now we will create a folder called templates, and inside that, we will create a welcome.html file. It has a simple code that creates buttons for every provider.

 

welcome.html

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport">
      <title>Authlib </title>
   </head>
   <body>
      <p align="left">
         <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="instagram/">
         <img id="instagram"
         src="https://img.shields.io/badge/Instagram-Connect-brightgreen?style=for-the-badge&labelColor=black&logo=twitter"
            alt="Instagram"> <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>

 

For immense and clear understanding of HTML, we recommend going through our guided learning of HTML.

 

Now we will create  a Flask app

from flask import Flask, render_template
app = Flask(__name__)
 
app.secret_key = 'CODINGNINJAS'
 
app.config['SERVER_NAME'] = 'localhost:5000'
 
@app.route('/')
def index():
    return render_template('welcome.html')
 
if __name__ == "__main__":
    app.run(debug=True)
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Learn more about creating first app in flask application.

We will run the server by executing the above python script to ensure that the application runs successfully and the welcome.html page is displayed. 

 

Output: 

 

Initialising the OAuth in Flask application

from flask import Flask, render_template
from authlib.integrations.flask_client import OAuth
 
app = Flask(__name__)
 
app.secret_key = 'CODINGNINJAS'
 
app.config['SERVER_NAME'] = 'localhost:5000'

# Initializing OAuth with the following command
oauth = OAuth(app)
 
@app.route('/')
def index():
    return render_template('welcome.html')
 
if __name__ == "__main__":
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Setting up OAuth in Flask for Instagram

from flask import Flask, render_template, url_for, redirect
from authlib.integrations.flask_client import OAuth
import os
 
app = Flask(__name__)
app.secret_key = 'CODINGNINJAS'
 
'''
    Set SERVER_NAME to localhost as an Instagram callback
    URL does not accept 127.0.0.1
    Tip: Set the callback origin(site) for Facebook and Instagram to http://domain.com (or your domain name) because this service does not support 127.0.0.1 or localhost.
'''
 
app.config['SERVER_NAME'] = 'localhost:5000'
 
oauth = OAuth(app)
 
@app.route('/')
def index():
    return render_template('welcome.html')
   
@app.route('/instagram/')
def instagram():
   
    # Instagram Oauth Config
    INSTAGRAM_CLIENT_ID = os.environ.get('INSTAGRAM_CLIENT_ID')
    INSTAGRAM_CLIENT_SECRET = os.environ.get('INSTAGRAM_CLIENT_SECRET')
    oauth.register(
        name='instagram',
        client_id=INSTAGRAM_CLIENT_ID,
 request_token_url='https://api.instagram.com/oauth/request_token',
        request_token_params=None,
        access_token_url='https://api.instagram.com/oauth/access_token',
        access_token_params=None,
        authorize_url='https://api.instagram.com/oauth/authenticate',
        authorize_params=None,
        api_base_url='https://api.instagram.com/1.1/',
        client_kwargs=None,
    )
    redirect_uri = url_for('instagram_auth', _external=True)
    return oauth.instagram.authorize_redirect(redirect_uri)
 
@app.route('/instagram/auth/')
def instagram_auth():
    token = oauth.instagram.authorize_access_token()
    resp = oauth.instagram.get('account/verify_credentials.json')
    profile = resp.json()
    print(" instagram User", profile)
    return redirect('/')
 
  if __name__ == "__main__":
    app.run(debug=True)
You can also try this code with Online Python Compiler
Run Code

 

Setting up OAuth in Flask For Google

from flask import Flask, render_template, url_for, redirect
from authlib.integrations.flask_client import OAuth
import os
 
app = Flask(__name__)
app.secret_key = 'CODINGNINJAS'
 
'''
    Set SERVER_NAME to localhost as twitter callback
    URL does not accept 127.0.0.1
    Tip: set callback origin(site) for Facebook and Instagram
    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('welcome.html')
 
@app.route('/google/')
def google():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)
You can also try this code with Online Python Compiler
Run Code

 

Setting up OAuth in Flask for Facebook

# Facebook Oauth Configuration
    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'},WSGI
    )
    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)
You can also try this code with Online Python Compiler
Run Code

 

On running the Flask application, we get the results on http://localhost:5000/

Must Read, PHP For Loop

FAQs

  1. What is the difference between OAuth and JWT?
    Ans. JWT is essentially a token format. JWT is a token that may be used as part of the OAuth authorization protocol. Server-side and client-side storage are used in OAuth. If we want to make a proper log-out, we'll need to use OAuth2.
     
  2. What is an OAuth access token?
    Ans. The OAuth client's string to send requests to the resource server is known as an OAuth Access Token. Access tokens do not have to be in a certain format, and in fact, different OAuth servers use a variety of forms for their access tokens. 
     
  3. What is an OAuth authorization code?
    Ans. The authorization code is a one-time code that the client will use to obtain an access token. After a user has been authenticated, the code is acquired from the authorization server.

Key Takeaways

This article extensively discussed OAuth authentication and how OAuth in Flask is incorporated. 

We hope this blog has helped you enhance your knowledge of the Open authentication through OAuth in Flask. For learning more about Templates in FlaskCookies handling in Flask, and more, check out Code Studio's blog site. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass