0
0
Flaskframework~5 mins

OAuth2 overview in Flask

Choose your learning style9 modes available
Introduction

OAuth2 helps apps let users log in safely using accounts from other services like Google or Facebook. It keeps passwords private and shares only what is needed.

You want users to sign in using their Google or Facebook accounts.
Your app needs to access user data from another service with permission.
You want to avoid storing user passwords in your app.
You want a secure way to let users grant limited access to their data.
You want to improve user experience by simplifying login steps.
Syntax
Flask
from flask import Flask, redirect, url_for
from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
app.secret_key = 'random_secret_key'
oauth = OAuth(app)

# Register OAuth provider
google = oauth.register(
    name='google',
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'},
)

@app.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
    token = google.authorize_access_token()
    user_info = google.get('userinfo').json()
    return f"Hello, {user_info['email']}!"

This example uses the Authlib library to handle OAuth2 in Flask.

You need to register your app with the OAuth provider to get client_id and client_secret.

Examples
Registering Google as an OAuth2 provider with necessary URLs and scopes.
Flask
google = oauth.register(
    name='google',
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'},
)
Redirects user to Google login page to start OAuth2 flow.
Flask
@app.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)
Handles callback from Google, gets user info, and greets the user.
Flask
@app.route('/authorize')
def authorize():
    token = google.authorize_access_token()
    user_info = google.get('userinfo').json()
    return f"Hello, {user_info['email']}!"
Sample Program

This Flask app lets users log in with Google using OAuth2. The homepage shows a login link. Clicking it starts the OAuth2 login. After login, it greets the user by email.

Flask
from flask import Flask, redirect, url_for
from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
app.secret_key = 'random_secret_key'
oauth = OAuth(app)

google = oauth.register(
    name='google',
    client_id='YOUR_CLIENT_ID',
    client_secret='YOUR_CLIENT_SECRET',
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
    api_base_url='https://www.googleapis.com/oauth2/v1/',
    client_kwargs={'scope': 'openid email profile'},
)

@app.route('/')
def homepage():
    return '<a href="/login">Login with Google</a>'

@app.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return google.authorize_redirect(redirect_uri)

@app.route('/authorize')
def authorize():
    token = google.authorize_access_token()
    user_info = google.get('userinfo').json()
    return f"Hello, {user_info['email']}!"
OutputSuccess
Important Notes

Replace 'YOUR_CLIENT_ID' and 'YOUR_CLIENT_SECRET' with your actual credentials from Google.

OAuth2 flow involves redirecting users to the provider and handling callbacks securely.

Always keep your secret keys safe and never expose them publicly.

Summary

OAuth2 lets apps use other services for login without handling passwords.

Flask with Authlib makes OAuth2 integration easier.

Users grant permission, and your app gets limited access to their info.