
Module 9 Exercises: Securing the Perimeter
Practical exercises to challenge your understanding of JWT, OAuth2, and role-based permissions.
Module 9 Exercises: Securing the Perimeter
Authentication and Authorization are the dual gates to your application. These exercises will help you ensure those gates are both powerful and precise.
Exercise 1: The Token Decoder
You have received a JWT string in your FastAPI endpoint via the token variable.
Write the code needed to:
- Decode the token using
SECRET_KEYand theHS256algorithm. - Extract the
"user_id"from the payload. - Handle the case where the token is expired (hint:
jose.ExpiredSignatureError).
Exercise 2: Implementing the Admin Guard
You are building a Bank API. You want to create a dependency called require_admin.
It should:
- Depend on
get_current_user. - Check if the user's
is_adminattribute isTrue. - If not, raise a
403 Forbiddenerror with the detail"Financial data restricted to administrators."
Exercise 3: Scope Design
Imagine you are building a "Music Streaming" API like Spotify.
Suggest three Scopes (not Roles) that a third-party application might request from a user.
Example: read:private_playlists.
Self-Correction / Discussion
Exercise 1 Answer:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
user_id = payload.get("user_id")
except ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token has expired")
except JWTError:
raise HTTPException(status_code=401, detail="Could not validate credentials")
Exercise 2 Answer:
def require_admin(current_user: User = Depends(get_current_user)):
if not current_user.is_admin:
raise HTTPException(
status_code=403,
detail="Financial data restricted to administrators."
)
return current_user
Exercise 3 Answer:
read:user_top_artistswrite:public_playlistsread:user_email_address
Summary of Module 9
You have built the most critical layer of a production system.
- JWT: You understand stateless authentication.
- OAuth2: You can implement the industry standard flow.
- RBAC: You can control permissions with fine-grained dependencies.
In Module 10: Database Integration, we will leave the world of identity and move back to data, learning how to connect FastAPI to SQL and NoSQL databases for persistent storage.