Token-Based Authentication (JWT)
APIs commonly use token-based auth because they’re stateless.
What is JWT?
Section titled “What is JWT?”JWT = JSON Web Token.
A JWT is a signed string that typically contains:
- user identity (subject)
- expiration time
- optional claims (roles, permissions)
Common flow
Section titled “Common flow” sequenceDiagram
participant C as Client
participant A as API
C->>A: POST /auth/login (username+password)
A-->>C: 200 {access_token}
C->>A: GET /api/profile (Authorization: Bearer token)
A-->>C: 200 {profile}
Flask options
Section titled “Flask options”Popular library:
- Flask-JWT-Extended
Install:
pip install Flask-JWT-ExtendedHigh-level usage (conceptual)
Section titled “High-level usage (conceptual)”- create token on login
- require token on protected API routes
Security notes
Section titled “Security notes”- Keep JWT secret keys safe (env vars)
- Use short expiration times
- For browser-based apps, be careful where you store tokens (XSS risk)
- Consider refresh tokens for longer sessions
JWT is powerful, but misuse can create security issues.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading