Dokumentacja

Dowiedz się czym jest JWT i jak go używać w aplikacjach.

Czym jest JWT?

JSON Web Token (JWT) to otwarty standard (RFC 7519) do bezpiecznego przesyłania informacji między stronami jako obiekt JSON.

Struktura JWT

JWT składa się z trzech części oddzielonych kropkami: Header.Payload.Signature.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Nagłówek

Zawiera metadane tokena: algorytm (alg) i typ (typ).

Payload

Zawiera claims (oświadczenia) dotyczące encji i metadane.

Podpis

Służy do weryfikacji, czy token nie został zmodyfikowany.

Typowe Claims

iss (Issuer): identyfikuje wystawcę tokena

sub (Subject): identyfikuje podmiot tokena

aud (Audience): identyfikuje odbiorców tokena

exp (Expiration): czas wygaśnięcia (timestamp Unix)

nbf (Not Before): czas przed którym token nie powinien być akceptowany

iat (Issued At): czas wydania tokena

Obsługiwane Algorytmy

JWT obsługuje różne algorytmy podpisu.

HS256 / HS384 / HS512

HMAC z SHA-2 — podpis symetryczny

RS256 / RS384 / RS512

RSA z SHA-2 — podpis asymetryczny

ES256 / ES384 / ES512

ECDSA z SHA-2 — asymetryczny podpis krzywej eliptycznej

EdDSA (Ed25519)

EdDSA — nowoczesny podpis krzywej eliptycznej Ed25519

Przykłady Kodu

Gotowe fragmenty kodu dla JWT w różnych językach.

JavaScript (Node.js)
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);
TypeScript (jose)
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);
Python
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)
Java
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();
Go
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)
Ruby
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]
PHP
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);
Rust
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),
)?;
C# (.NET)
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 _);
Swift
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)