Scadenza dei JWT e regole di validazione
Comprenda come viene controllata la durata dei JWT tramite claim temporali come exp, nbf e iat, e come i validator rifiutano i token scaduti o prematuri.
Scadenza dei JWT e regole di validazione è una lezione Spring Security 6 & JWT Authentication gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Security 6 & JWT Authentication, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Tokens Need a Lifetime
A JWT is a bearer credential: whoever holds it is trusted. If a token never expired, a leaked token would grant access forever.
Time-based claims limit the damage window by making tokens valid only for a short period.
The exp Claim
The exp (expiration) claim is a Unix timestamp. After this moment the token is invalid and must be rejected.
{
'sub': 'user123',
'exp': 1717200000
}The iat Claim
The iat (issued at) claim records when the token was created. It is useful for measuring token age and for revoking all tokens issued before a certain time.
{
'sub': 'user123',
'iat': 1717196400,
'exp': 1717200000
}The nbf Claim
The nbf (not before) claim defines the earliest time a token becomes valid. A token used before its nbf time must be rejected, which is handy for tokens scheduled to activate later.
{
'sub': 'user123',
'nbf': 1717196400,
'exp': 1717200000
}Choosing an Expiration Window
Short lifetimes are safer but force frequent re-authentication. A common pattern is:
- Access token: 5-15 minutes
- Refresh token: days or weeks
The short access token limits exposure; the refresh token keeps the user logged in.
Setting exp When Issuing
When you build a token, set exp relative to now. Here a 15-minute access token is created using a JWT library.
const now = Math.floor(Date.now() / 1000);
const payload = {
sub: 'user123',
iat: now,
exp: now + 15 * 60
};Validating exp on the Server
On every request the server checks exp against the current time. Most libraries do this automatically and throw if the token is expired.
try {
const claims = verify(token, secret);
} catch (err) {
if (err.name === 'TokenExpiredError') {
// reject with 401
}
}Clock Skew
Servers do not always have perfectly synchronized clocks. A small leeway (a few seconds) prevents valid tokens from being rejected because of minor clock differences.
verify(token, secret, { clockTolerance: 5 });exp Is Not Encryption
Remember: a JWT payload is only encoded, not encrypted. The exp claim stops the server from accepting the token, but anyone can read the claims. Never put secrets in the payload.
Reacting to Expiry on the Client
When the client gets a 401 due to expiry, it should silently request a new access token using the refresh token, then retry the original request.
if (response.status === 401) {
const fresh = await refreshAccessToken();
return retryWith(fresh);
}Common Validation Mistakes
Watch out for these errors:
- Forgetting to validate exp at all
- Using milliseconds instead of seconds for the timestamp
- Setting an excessively long lifetime
- Ignoring nbf, allowing premature use
Quick Check
Test your knowledge of JWT time claims.
Recap
You learned how JWT lifetime is controlled:
expsets the expiration;iatrecords issue time;nbfsets earliest validity- Use short access tokens plus longer refresh tokens
- Allow small clock skew with leeway
- exp does not encrypt the payload
Proper expiration handling keeps stolen tokens useful for only a brief window.
Domande Frequenti
La lezione «Scadenza dei JWT e regole di validazione» è gratuita?
Sì — il testo completo di «Scadenza dei JWT e regole di validazione» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Security 6 & JWT Authentication, passa a CoddyKit PRO. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.
Cosa imparerò in «Scadenza dei JWT e regole di validazione»?
Comprenda come viene controllata la durata dei JWT tramite claim temporali come exp, nbf e iat, e come i validator rifiutano i token scaduti o prematuri. Eserciti Spring Security 6 & JWT Authentication con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Spring Security 6 & JWT Authentication?
Non è richiesta alcuna esperienza precedente. Spring Security 6 & JWT Authentication su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Scadenza dei JWT e regole di validazione»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Spring Security 6 & JWT Authentication?
Sì. Ogni lezione Spring Security 6 & JWT Authentication include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Comprendere i JSON Web Token
- Struttura e claim dei JWT
- Firma e verifica dei JWT
- Scadenza dei JWT e regole di validazione