Skip to content

Token-Based Authentication (JWT)

APIs commonly use token-based auth because they’re stateless.

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

false


  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}

false

Flask options

Popular library:

  • Flask-JWT-Extended

Install:

pip install Flask-JWT-Extended
pip install Flask-JWT-Extended

High-level usage (conceptual)

  • create token on login
  • require token on protected API routes

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

Exercise 1 – Create a Flask App

Exercise 2 – Dynamic Route

Exercise 3 – Return JSON

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did