Documentation
Learn about JWT and how to use it in your applications.
What is JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
JWT Structure
A JWT consists of three parts separated by dots: Header.Payload.Signature. Each part is Base64URL encoded.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cHeader
Contains metadata about the token, typically the signing algorithm (alg) and token type (typ).
Payload
Contains the claims. Claims are statements about an entity (typically the user) and additional metadata.
Signature
Used to verify the token hasn't been altered. Created by signing the encoded header and payload with a secret or private key.
Common Claims
iss (Issuer): Identifies who issued the token
sub (Subject): Identifies the subject of the token
aud (Audience): Identifies the recipients for which the token is intended
exp (Expiration): Expiration time (Unix timestamp)
nbf (Not Before): Time before which the token must not be accepted
iat (Issued At): Time at which the token was issued
Supported Algorithms
JWT supports various signing algorithms for different use cases.
HS256 / HS384 / HS512
HMAC with SHA-2 — symmetric signing (same secret for sign and verify)
RS256 / RS384 / RS512
RSA with SHA-2 — asymmetric signing (private key signs, public key verifies)
ES256 / ES384 / ES512
ECDSA with SHA-2 — elliptic curve asymmetric signing
EdDSA (Ed25519)
EdDSA — modern elliptic curve signing using Ed25519
Code Examples
Ready-to-use code snippets for working with JWTs in various programming languages.
const jwt = require('jsonwebtoken');
// Sign
const token = jwt.sign(
{ sub: '1234567890', name: 'John Doe' },
'your-secret-key',
{ algorithm: 'HS256', expiresIn: '1h' }
);
// Verify
const decoded = jwt.verify(token, 'your-secret-key');
console.log(decoded);import { SignJWT, jwtVerify } from 'jose';
// Sign
const secret = new TextEncoder().encode('your-secret-key');
const token = await new SignJWT({ sub: '1234567890', name: 'John Doe' })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('1h')
.sign(secret);
// Verify
const { payload } = await jwtVerify(token, secret);
console.log(payload);import jwt
# Sign
token = jwt.encode(
{"sub": "1234567890", "name": "John Doe"},
"your-secret-key",
algorithm="HS256"
)
# Verify
decoded = jwt.decode(token, "your-secret-key", algorithms=["HS256"])
print(decoded)import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
// Sign
String token = Jwts.builder()
.setSubject("1234567890")
.claim("name", "John Doe")
.signWith(SignatureAlgorithm.HS256, "your-secret-key")
.compact();
// Verify
Claims claims = Jwts.parser()
.setSigningKey("your-secret-key")
.parseClaimsJws(token)
.getBody();import (
"github.com/golang-jwt/jwt/v5"
)
// Sign
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "1234567890",
"name": "John Doe",
})
tokenString, err := token.SignedString([]byte("your-secret-key"))
// Verify
parsed, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
return []byte("your-secret-key"), nil
})
claims := parsed.Claims.(jwt.MapClaims)require 'jwt'
payload = { sub: '1234567890', name: 'John Doe' }
# Sign
token = JWT.encode(payload, 'your-secret-key', 'HS256')
# Verify
decoded = JWT.decode(token, 'your-secret-key', true, algorithm: 'HS256')
puts decoded[0]use Firebase\JWT\JWT;
$payload = [
'sub' => '1234567890',
'name' => 'John Doe',
];
// Sign
$token = JWT::encode($payload, 'your-secret-key', 'HS256');
// Verify
$decoded = JWT::decode($token, new Key('your-secret-key', 'HS256'));
print_r($decoded);use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
// Sign
let token = encode(
&Header::new(Algorithm::HS256),
&serde_json::json!({"sub": "1234567890", "name": "John Doe"}),
&EncodingKey::from_secret("your-secret-key".as_ref()),
)?;
// Verify
let token_data = decode::<serde_json::Value>(
&token,
&DecodingKey::from_secret("your-secret-key".as_ref()),
&Validation::new(Algorithm::HS256),
)?;using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("your-secret-key"));
// Sign
var token = new JwtSecurityToken(
claims: new[] { new Claim("sub", "1234567890"), new Claim("name", "John Doe") },
signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
// Verify
var principal = new JwtSecurityTokenHandler().ValidateToken(tokenString,
new TokenValidationParameters { ValidateIssuerSigningKey = true,
IssuerSigningKey = securityKey, ValidateIssuer = false, ValidateAudience = false },
out _);import JWT
// Sign
let payload = JWTPayload(sub: "1234567890", name: "John Doe")
let signer = JWTSigner.hs256(key: Data("your-secret-key".utf8))
let token = try signer.sign(payload)
// Verify
let verifier = JWTVerifier.hs256(key: Data("your-secret-key".utf8))
let verified = try verifier.verify(token)