Practice & Assessment
Test your understanding of Authentication and Security
Multiple Choice Questions
5Why should you use `pwd_context.verify()` instead of comparing password hashes with `==`?
A JWT's `exp` claim is set to a past timestamp. What happens when `jwt.decode()` is called?
Why can't you use `allow_origins=['*']` together with `allow_credentials=True` in CORSMiddleware?
What claim does the FastAPI documentation recommend using to store the user identifier in a JWT payload?
When using slowapi for rate limiting, why is `request: Request` required as a route parameter?
Coding Challenges
1Secure Auth API with JWT Login
Build a FastAPI authentication system. Implement: POST `/register` accepting `{email, password}` — hash the password with bcrypt and store in an in-memory dict keyed by email, return `{email}` with 201. POST `/token` accepting OAuth2PasswordRequestForm — verify credentials and return `{access_token, token_type}` JWT containing `sub=email` expiring in 15 minutes, or 401 on failure. GET `/me` protected by `get_current_user` dependency that decodes the token, looks up the user, and returns `{email}` or 401 if invalid/expired. Add CORS allowing `http://localhost:3000`. Inputs: form data for /token, JSON for /register. Outputs: user email on /me. Estimated time: 25-30 minutes.
Mini Project
Secure Notes API with JWT Auth
Extend the Notes API from Module 1 with full security. Add User model (email, hashed_password) with register and login endpoints. Implement JWT creation and verification using python-jose HS256. Create `get_current_user` dependency that decodes the bearer token, fetches the user from the in-memory store, and raises 401 for missing or invalid tokens. Protect all note mutation routes (POST, PATCH, DELETE) with this dependency. Add user ownership: each note has an `owner_email` field; only the owner can update or delete their own notes (403 Forbidden otherwise). Add CORSMiddleware allowing `http://localhost:3000`. Apply a 20-per-minute rate limit to the `/register` and `/token` endpoints using slowapi. Return correct status codes throughout.
