Cos'è la codifica JWT?
La codifica JWT è il processo di creazione di un JSON Web Token — una stringa compatta e sicura per gli URL che trasporta un insieme di dichiarazioni firmate con una chiave crittografica. Il risultato è un token a tre parti (intestazione.payload.firma) definito da RFC 7519 che i server possono verificare senza mantenere lo stato della sessione. La codifica JWT online ti consente di creare e firmare token direttamente nel tuo browser per test e sviluppo.
L'intestazione dichiara l'algoritmo di firma (ad es. HS256) e il tipo di token. Il payload contiene dichiarazioni — coppie chiave-valore come il soggetto (sub), il tempo di scadenza (exp) e qualsiasi dato personalizzato di cui la tua applicazione ha bisogno. Entrambe le parti vengono serializzate come JSON, quindi codificate in base64url. La firma viene calcolata sull'intestazione e il payload codificati utilizzando una chiave segreta, vincolando tutti e tre i segmenti insieme.
A differenza dei cookie di sessione, i JWT sono autonomi: il verificatore non ha bisogno di interrogare un database o chiamare un servizio esterno. Ciò rende l'autenticazione basata su JWT popolare nelle API REST, nei microservizi e nelle applicazioni a pagina singola dove l'autorizzazione senza stato riduce la latenza e semplifica la scalabilità orizzontale.
RFC 7519 — JSON Web Token (JWT) →RFC 7515 — JSON Web Signature (JWS) →
Perché usare un codificatore JWT?
La generazione manuale di JWT richiede la codifica base64url, la serializzazione JSON e il calcolo HMAC. Questo strumento gestisce tutti e tre i passaggi istantaneamente in modo che tu possa concentrarti su come ottenere le giuste dichiarazioni.
Casi d'uso del codificatore JWT
HS256 vs HS384 vs HS512: Confronto degli algoritmi HMAC
Tutti e tre gli algoritmi utilizzano HMAC (Hash-based Message Authentication Code) con un segreto condiviso. La differenza è nella funzione hash sottostante, che influenza la lunghezza della firma e il margine di sicurezza. Per la maggior parte delle applicazioni, HS256 fornisce una sicurezza sufficiente. Scegli HS384 o HS512 quando i requisiti di conformità (ad es. FIPS-140) richiedono un hash più forte o quando i tuoi token portano decisioni di autorizzazione di alto valore.
| Algoritmo | Hash | Firma | Velocità | Uso tipico |
|---|---|---|---|---|
| HS256 | SHA-256 | 32 B | Fastest | General purpose, default for most libraries |
| HS384 | SHA-384 | 48 B | Fast | Higher security margin, FIPS-140 compliant |
| HS512 | SHA-512 | 64 B | Fast | Maximum HMAC security, large payloads |
Riferimento alle dichiarazioni JWT standard
RFC 7519 definisce sette dichiarazioni registrate. Nessuna è obbligatoria, ma utilizzarle correttamente migliora l'interoperabilità e la sicurezza. La dichiarazione exp è particolarmente importante — i token senza scadenza sono validi indefinitamente se il segreto non viene ruotato.
| Dichiarazione | Nome | Descrizione | Esempio |
|---|---|---|---|
| iss | Issuer | Who issued the token | "auth.example.com" |
| sub | Subject | Who the token represents | "user-123" |
| aud | Audience | Intended recipient service | "api.example.com" |
| exp | Expiration | Unix timestamp — token invalid after this time | 1717203600 |
| nbf | Not Before | Unix timestamp — token invalid before this time | 1717200000 |
| iat | Issued At | Unix timestamp when the token was created | 1717200000 |
| jti | JWT ID | Unique token identifier for revocation tracking | "a1b2c3d4" |
Codifica JWT nel codice
Questi esempi mostrano come creare e firmare i JWT a livello di programmazione. Ogni frammento produce un token valido firmato con HS256. Per i sistemi di produzione, impostare sempre la dichiarazione exp e utilizzare un segreto crittograficamente casuale di almeno 256 bit.
async function signJWT(payload, secret, alg = 'HS256') {
const header = { alg, typ: 'JWT' }
const enc = new TextEncoder()
// Base64url encode header and payload
const b64url = (obj) =>
btoa(JSON.stringify(obj)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
const h = b64url(header)
const p = b64url(payload)
// Sign with HMAC-SHA256
const key = await crypto.subtle.importKey(
'raw', enc.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
)
const sig = await crypto.subtle.sign('HMAC', key, enc.encode(`${h}.${p}`))
const s = btoa(String.fromCharCode(...new Uint8Array(sig)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
return `${h}.${p}.${s}`
}
// Usage
const token = await signJWT(
{ sub: 'user-123', name: 'Alice', iat: Math.floor(Date.now() / 1000) },
'your-256-bit-secret'
)
// → "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi..."import jwt
import time
payload = {
"sub": "user-123",
"name": "Alice",
"iat": int(time.time()),
"exp": int(time.time()) + 3600, # expires in 1 hour
}
# Sign with HS256 (default)
token = jwt.encode(payload, "your-256-bit-secret", algorithm="HS256")
# → "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi..."
# Verify and decode
decoded = jwt.decode(token, "your-256-bit-secret", algorithms=["HS256"])
# → {"sub": "user-123", "name": "Alice", "iat": 1717200000, "exp": 1717203600}const jwt = require('jsonwebtoken')
const payload = {
sub: 'user-123',
name: 'Alice',
role: 'admin',
}
// Sign — iat is added automatically
const token = jwt.sign(payload, 'your-256-bit-secret', {
algorithm: 'HS256',
expiresIn: '1h', // sets exp claim
issuer: 'auth.example.com', // sets iss claim
})
// Verify
const decoded = jwt.verify(token, 'your-256-bit-secret')
// → { sub: 'user-123', name: 'Alice', role: 'admin', iat: ..., exp: ... }package main
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
func main() {
claims := jwt.MapClaims{
"sub": "user-123",
"name": "Alice",
"iat": time.Now().Unix(),
"exp": time.Now().Add(time.Hour).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, _ := token.SignedString([]byte("your-256-bit-secret"))
fmt.Println(signed)
// → eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOi...
}