Bird
Raised Fist0
Flaskframework~20 mins

OAuth2 overview in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
OAuth2 Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main purpose of OAuth2 in web applications?

OAuth2 is widely used in web apps. What does it mainly help with?

AIt allows users to log in using credentials from another service without sharing passwords.
BIt encrypts all data sent between client and server automatically.
CIt manages database connections for faster queries.
DIt provides a way to write server-side code in multiple languages.
Attempts:
2 left
💡 Hint

Think about how you can sign into apps using Google or Facebook accounts.

❓ component_behavior
intermediate
2:00remaining
What happens after a user grants permission in OAuth2 flow?

In OAuth2, after the user allows access, what does the client receive to continue?

AThe user's password to authenticate future requests.
BA direct connection to the user's database.
CA refresh token that immediately expires.
DAn access token that the client uses to access protected resources.
Attempts:
2 left
💡 Hint

Think about what the client needs to call APIs on behalf of the user.

📝 Syntax
advanced
2:00remaining
Identify the correct Flask route to start OAuth2 authorization with a provider.

Which Flask route code correctly redirects the user to the OAuth2 provider's authorization URL?

Flask
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)
Aauthorization_url
Breturn authorization_url
Credirect(authorization_url)
Dredirect('/home')
Attempts:
2 left
💡 Hint

Flask has a function to send users to another URL.

❓ state_output
advanced
2:00remaining
What is the value of 'token' after exchanging code in OAuth2?

Given this Flask snippet exchanging an authorization code, what is the value of token?

Flask
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
AA string token like 'ya29.a0AfH6SM...' used to access APIs.
BThe original authorization code sent by the provider.
CA JSON object containing user profile information.
DAn error message string if the code is invalid.
Attempts:
2 left
💡 Hint

What does the token endpoint return after exchanging the code?

🔧 Debug
expert
2:00remaining
Why does this OAuth2 Flask callback raise a KeyError?

Consider this Flask callback code snippet. Why does it raise a KeyError?

Flask
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
AThe 'code' variable is None because the URL has no 'code' parameter.
BThe response JSON does not contain 'access_token' key, causing KeyError.
CThe requests.post call is missing headers, causing a failed request.
DFlask routes cannot return strings directly, causing an error.
Attempts:
2 left
💡 Hint

Check what happens if the token endpoint returns an error response.

Practice

(1/5)
1. What is the main purpose of OAuth2 in a Flask application?
easy
A. Store user passwords securely in the Flask app database
B. Allow users to log in using external services without sharing passwords
C. Encrypt all data sent between client and server
D. Automatically create user accounts without permission

Solution

  1. Step 1: Understand OAuth2 role

    OAuth2 lets apps use other services for login without handling user passwords directly.
  2. Step 2: Identify correct purpose in Flask context

    Flask apps use OAuth2 to let users sign in via external providers safely.
  3. Final Answer:

    Allow users to log in using external services without sharing passwords -> Option B
  4. Quick Check:

    OAuth2 = external login without password sharing [OK]
Hint: OAuth2 means login without storing passwords [OK]
Common Mistakes:
  • Thinking OAuth2 stores passwords
  • Confusing OAuth2 with encryption
  • Assuming OAuth2 creates accounts automatically
2. Which Flask extension is commonly used to simplify OAuth2 integration?
easy
A. Flask-WTF
B. Flask-SQLAlchemy
C. Authlib
D. Flask-Mail

Solution

  1. Step 1: Recall Flask extensions for OAuth2

    Authlib is a popular Flask extension designed to handle OAuth2 easily.
  2. Step 2: Eliminate unrelated extensions

    Flask-SQLAlchemy manages databases, Flask-WTF handles forms, Flask-Mail sends emails, so they don't handle OAuth2.
  3. Final Answer:

    Authlib -> Option C
  4. Quick Check:

    OAuth2 in Flask = Authlib [OK]
Hint: Authlib is for OAuth2 in Flask [OK]
Common Mistakes:
  • Choosing Flask-SQLAlchemy for OAuth2
  • Confusing form or mail extensions with OAuth2
  • Not knowing Authlib's purpose
3. Given this Flask OAuth2 code snippet, what will 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'
medium
A. Empty dictionary because token is invalid
B. An error because 'userinfo' endpoint is missing
C. A string 'Logged in' printed to console
D. A dictionary with user's email, name, and profile info

Solution

  1. 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.
  2. Step 2: Analyze user_info content

    The google.get('userinfo').json() returns a dictionary with user details like email and name.
  3. Final Answer:

    A dictionary with user's email, name, and profile info -> Option D
  4. Quick Check:

    OAuth2 userinfo call = user data dict [OK]
Hint: OAuth2 userinfo returns user data dictionary [OK]
Common Mistakes:
  • Expecting a string instead of dictionary
  • Assuming endpoint is missing
  • Thinking token is invalid without error
4. What is wrong with this Flask OAuth2 snippet?
@app.route('/authorize')
def authorize():
    token = google.authorize_access_token
    user_info = google.get('userinfo').json()
    return user_info
medium
A. Missing parentheses when calling authorize_access_token
B. Using 'userinfo' instead of 'user_info' endpoint
C. Returning JSON directly causes syntax error
D. No redirect URI specified in authorize route

Solution

  1. Step 1: Check method call syntax

    The code uses google.authorize_access_token without parentheses, so it references the method, not calls it.
  2. Step 2: Understand effect of missing parentheses

    Without calling the method, token is a function object, causing errors later.
  3. Final Answer:

    Missing parentheses when calling authorize_access_token -> Option A
  4. Quick Check:

    Method call needs () [OK]
Hint: Always add () to call methods [OK]
Common Mistakes:
  • Forgetting parentheses on method calls
  • Confusing endpoint names
  • Assuming JSON return causes error
5. You want your Flask app to request only the user's email and profile during OAuth2 login with Google. Which scope value should you use when registering the OAuth client?
hard
A. 'openid email profile'
B. 'read write'
C. 'user:email user:profile'
D. 'email profile openid offline_access'

Solution

  1. Step 1: Identify correct OAuth2 scopes for Google

    Google uses 'openid email profile' scopes to request user's email and profile info.
  2. Step 2: Eliminate incorrect scopes

    'read write' is generic, 'user:email user:profile' is GitHub style, 'offline_access' requests refresh tokens, not needed here.
  3. Final Answer:

    'openid email profile' -> Option A
  4. Quick Check:

    Google OAuth2 scopes for email/profile = 'openid email profile' [OK]
Hint: Use 'openid email profile' for Google OAuth2 scopes [OK]
Common Mistakes:
  • Using GitHub or generic scopes
  • Adding unnecessary offline_access scope
  • Confusing scope syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard