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.
OAuth2 overview in 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.
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 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.
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']}!"
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.
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.
Practice
Solution
Step 1: Understand OAuth2 role
OAuth2 lets apps use other services for login without handling user passwords directly.Step 2: Identify correct purpose in Flask context
Flask apps use OAuth2 to let users sign in via external providers safely.Final Answer:
Allow users to log in using external services without sharing passwords -> Option BQuick Check:
OAuth2 = external login without password sharing [OK]
- Thinking OAuth2 stores passwords
- Confusing OAuth2 with encryption
- Assuming OAuth2 creates accounts automatically
Solution
Step 1: Recall Flask extensions for OAuth2
Authlib is a popular Flask extension designed to handle OAuth2 easily.Step 2: Eliminate unrelated extensions
Flask-SQLAlchemy manages databases, Flask-WTF handles forms, Flask-Mail sends emails, so they don't handle OAuth2.Final Answer:
Authlib -> Option CQuick Check:
OAuth2 in Flask = Authlib [OK]
- Choosing Flask-SQLAlchemy for OAuth2
- Confusing form or mail extensions with OAuth2
- Not knowing Authlib's purpose
print(user_info) output after successful login?from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
oauth = OAuth(app)
google = oauth.register('google', client_id='id', client_secret='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()
print(user_info)
return 'Logged in'Solution
Step 1: Understand OAuth2 flow in code
After login, the app gets an access token and calls 'userinfo' endpoint to get user data as JSON.Step 2: Analyze
Theuser_infocontentgoogle.get('userinfo').json()returns a dictionary with user details like email and name.Final Answer:
A dictionary with user's email, name, and profile info -> Option DQuick Check:
OAuth2 userinfo call = user data dict [OK]
- Expecting a string instead of dictionary
- Assuming endpoint is missing
- Thinking token is invalid without error
@app.route('/authorize')
def authorize():
token = google.authorize_access_token
user_info = google.get('userinfo').json()
return user_infoSolution
Step 1: Check method call syntax
The code usesgoogle.authorize_access_tokenwithout parentheses, so it references the method, not calls it.Step 2: Understand effect of missing parentheses
Without calling the method,tokenis a function object, causing errors later.Final Answer:
Missing parentheses when calling authorize_access_token -> Option AQuick Check:
Method call needs () [OK]
- Forgetting parentheses on method calls
- Confusing endpoint names
- Assuming JSON return causes error
scope value should you use when registering the OAuth client?Solution
Step 1: Identify correct OAuth2 scopes for Google
Google uses 'openid email profile' scopes to request user's email and profile info.Step 2: Eliminate incorrect scopes
'read write' is generic, 'user:email user:profile' is GitHub style, 'offline_access' requests refresh tokens, not needed here.Final Answer:
'openid email profile' -> Option AQuick Check:
Google OAuth2 scopes for email/profile = 'openid email profile' [OK]
- Using GitHub or generic scopes
- Adding unnecessary offline_access scope
- Confusing scope syntax
Ready to prove it?
Pass the test and this pattern moves unknown
