OAuth2 is widely used in web apps. What does it mainly help with?
Think about how you can sign into apps using Google or Facebook accounts.
OAuth2 lets users authorize apps to access their info from another service without sharing passwords, improving security and convenience.
In OAuth2, after the user allows access, what does the client receive to continue?
Think about what the client needs to call APIs on behalf of the user.
After permission, the client gets an access token to access user data securely without needing the password.
Which Flask route code correctly redirects the user to the OAuth2 provider's authorization URL?
from flask import Flask, redirect app = Flask(__name__) @app.route('/login') def login(): authorization_url = 'https://provider.com/oauth2/auth?client_id=abc&response_type=code' # Redirect user to authorization URL return redirect(authorization_url)
Flask has a function to send users to another URL.
Using redirect() sends the user to the OAuth2 provider's authorization page.
Given this Flask snippet exchanging an authorization code, what is the value of token?
from flask import Flask, request import requests app = Flask(__name__) @app.route('/callback') def callback(): code = request.args.get('code') response = requests.post('https://provider.com/oauth2/token', data={ 'client_id': 'abc', 'client_secret': 'xyz', 'code': code, 'grant_type': 'authorization_code' }) token = response.json().get('access_token') return token
What does the token endpoint return after exchanging the code?
The token endpoint returns an access token string used to authenticate API requests.
Consider this Flask callback code snippet. Why does it raise a KeyError?
from flask import Flask, request import requests app = Flask(__name__) @app.route('/callback') def callback(): code = request.args.get('code') response = requests.post('https://provider.com/oauth2/token', data={ 'client_id': 'abc', 'client_secret': 'xyz', 'code': code, 'grant_type': 'authorization_code' }) token = response.json()['access_token'] return token
Check what happens if the token endpoint returns an error response.
If the token endpoint returns an error or invalid response, the JSON may lack 'access_token', so accessing it directly raises KeyError.