Utiliser Bearer tokens pour API authentication
Bearer tokens sont sent en le Authorization en-tête: "Bearer <token>". Whoever holds le jeton peut access le API — protect it comme un mot de passe.
- 1
A Bearer token is a string that grants access to an API. It is sent as "Authorization: Bearer <token>". The server verifies the token (signature, expiration, scope) and grants or denies access. Bearer tokens can be JWTs, opaque tokens (validated via introspection endpoint), or API keys. Treat them as secrets — they grant the bearer access.
- 2 Encodeur JWT →
Create a JWT Bearer token. Set claims: sub (subject), exp (expiration), iat (issued at), scope (permissions). Sign with RS256 (asymmetric) or HS256 (symmetric). The token is self-contained — the server verifies the signature without a database lookup.
- 3 Décodeur JWT →
Décoder and verify a Bearer JWT. Check the signature, expiration (exp), not-before (nbf), issuer (iss), and audience (aud). Reject tokens with invalid signatures or expired timestamps. Never skip signature verification.
- 4
Use the JWT inspection workflow to decode, verify, and inspect all claims in a Bearer token.
Questions fréquentes
- JWT vs opaque token?
- JWT is self-contained (claims embedded, verifiable by signature) — no database lookup needed, but larger and cannot be revoked easily. Opaque token is a random string — the server must look it up (or call an introspection endpoint), but it can be revoked instantly and is smaller. Use JWT for stateless APIs, opaque for revocable access.
- How should I store Bearer tokens client-side?
- In memory (JavaScript variable) for short-lived tokens — most secure but lost on page refresh. In sessionStorage — survives refresh, cleared on tab close. In localStorage — persists across sessions, but vulnerable to XSS. Never in cookies without HttpOnly. For SPAs, use silent refresh (refresh token in HttpOnly cookie, access token in memory).