Module 9 Exercises: Securing the Perimeter

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:

  1. Decode the token using SECRET_KEY and the HS256 algorithm.
  2. Extract the "user_id" from the payload.
  3. 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:

  1. Depend on get_current_user.
  2. Check if the user's is_admin attribute is True.
  3. If not, raise a 403 Forbidden error 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:

  1. read:user_top_artists
  2. write:public_playlists
  3. read: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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn