JWT Code Examples
Sign and verify HS256 JSON Web Tokens in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Each example signs a token with HS256 carrying a user ID, a username, a role and the registered claims iss, aud, iat and exp (one hour), then verifies it. The guide explains what is random in a JWT, how large the signing secret must be and which checks verification must make; each language section then covers the library used.
Prefer no code? The interactive JWT generator does the same in the browser.
What a JWT is, and what in it is random
A JWT (RFC 7519) in its signed form (JWS, RFC 7515) is three Base64url parts joined by dots: a header such as {"alg":"HS256","typ":"JWT"}, a JSON payload of claims, and a signature over the first two parts. The header and payload are only encoded, not encrypted: anyone holding the token can read them, so never put passwords, card numbers or other secrets in the payload. Use JWE (RFC 7516) if the content itself must be hidden.
Nothing in a signed JWT needs randomness except the signing key and, optionally, a jti (token ID) used to detect replays or revoke single tokens. A jti of 128 random bits, such as a v4 UUID or 16 bytes from a CSPRNG, is enough to keep IDs unique.
The HS256 secret: at least 32 random bytes
RFC 7518 §3.2 requires an HMAC key at least as long as the hash output: 256 bits (32 bytes) for HS256, 384 bits for HS384, 512 bits for HS512. The bytes must come from a CSPRNG, for example openssl rand -base64 32, secrets.token_urlsafe(32) or crypto.randomBytes(32), and be loaded from an environment variable or secret manager.
A readable string such as your-256-bit-secret-key is 23 bytes and has far less entropy than its length suggests. Any single captured token lets an attacker test candidate secrets offline (hashcat has a dedicated JWT mode), and a recovered secret lets them mint tokens for any user and role. Some libraries refuse short keys: JJWT Keys.hmacShaKeyFor() throws WeakKeyException below 256 bits.
With HS256, every service that verifies tokens holds the secret and can therefore also create them. When verifiers are separate services or third parties, sign with RS256 (RSA, 2048 bits or more), ES256 (P-256) or EdDSA and give them only the public key.
What verification must check
- Pin the algorithm. Pass the expected algorithm list to the verifier. Accepting the token's own
algheader enables thenoneattack and RS256-to-HS256 key confusion (RFC 8725 §2.1, §3.1). - Check
expandnbfwith a small clock skew allowance (30–60 seconds), and keep access tokens short-lived: 5 to 15 minutes, renewed with a refresh token stored server-side. - Check
issandaud. Without the audience check, a token issued for one of your services is accepted by all of them.
Common mistakes
- Hard-coded fallback secrets.
process.env.JWT_SECRET || 'secret'silently signs production tokens with a published string when the variable is missing. Fail at startup instead. - Decoding instead of verifying.
jwt.decode()in jsonwebtoken and PyJWT withoptions={"verify_signature": False}return the claims without checking the signature; use them only for debugging. - Treating a JWT as revocable. A signed token stays valid until
exp. Logout and permission changes need short lifetimes, ajtideny list, or server-side sessions. - Storing tokens in
localStorage. Any XSS can read them; anHttpOnly,Secure,SameSitecookie limits that exposure.
Common Use Cases
- Stateless access tokens for REST and GraphQL APIs
- Short-lived service-to-service tokens between microservices
- ID and access tokens in OAuth 2.0 and OpenID Connect single sign-on
- Authenticating WebSocket and serverless function calls
- Signed, expiring links for email verification and password reset
JWT Code Examples in PHP
Generate secure JWT (JSON Web Tokens) in PHP using the Firebase JWT library. JWTs are ideal for stateless authentication, API authorization, and secure data transmission between parties.
<?php
require 'vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
// Secret key (store in environment variables)
$secret_key = getenv("JWT_SECRET"); // 32+ random bytes, e.g. openssl rand -base64 32
$issuer = "https://yourdomain.com";
$audience = "https://yourdomain.com";
// Create token payload
$payload = [
"iss" => $issuer, // Issuer
"aud" => $audience, // Audience
"iat" => time(), // Issued at
"nbf" => time(), // Not before
"exp" => time() + 3600, // Expiration (1 hour)
"data" => [
"user_id" => 123,
"username" => "john_doe",
"role" => "admin"
]
];
// Generate JWT
$jwt = JWT::encode($payload, $secret_key, 'HS256');
echo $jwt;
// Output: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwibmJmIjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDAsImRhdGEiOnsidXNlcl9pZCI6MTIzLCJ1c2VybmFtZSI6ImpvaG5fZG9lIiwicm9sZSI6ImFkbWluIn19.signature"
// Decode and verify JWT
try {
$decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
print_r($decoded->data);
} catch (Exception $e) {
echo "Invalid token: " . $e->getMessage();
}
How it works in PHP
This implementation uses the popular Firebase JWT library for PHP. The token consists of three parts: header, payload, and signature, separated by dots. Use HS256 (HMAC-SHA256) for symmetric signing or RS256 (RSA) for asymmetric signing. Always store secret keys in environment variables, never hardcode them.
Sample output
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwibmJmIjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDAsImRhdGEiOnsidXNlcl9pZCI6MTIzLCJ1c2VybmFtZSI6ImpvaG5fZG9lIiwicm9sZSI6ImFkbWluIn19.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
PHP notes
- Install with
composer require firebase/php-jwt; since v6,JWT::decode()takes aKeyobject, which fixes the algorithm per key. JWT::$leeway = 60;allows for clock skew when checkingexp,nbfandiat.- The library checks the signature and time claims; compare
$decoded->issand$decoded->audyourself.
JWT Code Examples in JavaScript
Generate secure JWT tokens in JavaScript using the jsonwebtoken library for Node.js. Perfect for Express.js APIs, authentication middleware, and stateless session management.
const jwt = require('jsonwebtoken');
// Secret key (store in environment variables)
const SECRET_KEY = process.env.JWT_SECRET; // 32+ random bytes; never fall back to a literal
if (!SECRET_KEY) throw new Error('JWT_SECRET is not set');
const ISSUER = 'https://yourdomain.com';
const AUDIENCE = 'https://yourdomain.com';
// Create token payload
const payload = {
user_id: 123,
username: 'john_doe',
role: 'admin'
};
// Generate JWT with options
const token = jwt.sign(payload, SECRET_KEY, {
algorithm: 'HS256',
expiresIn: '1h', // 1 hour
issuer: ISSUER,
audience: AUDIENCE
});
console.log(token);
// Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE2ODAwMDAwMDAsImV4cCI6MTY4MDAwMzYwMCwiaXNzIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20ifQ.signature"
// Verify and decode JWT
try {
const decoded = jwt.verify(token, SECRET_KEY, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: AUDIENCE
});
console.log(decoded);
} catch (err) {
console.error('Invalid token:', err.message);
}
// Express.js middleware example
const authenticateJWT = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1]; // Bearer token
if (!token) {
return res.sendStatus(401);
}
jwt.verify(token, SECRET_KEY, { algorithms: ['HS256'], issuer: ISSUER, audience: AUDIENCE }, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
How it works in JavaScript
The jsonwebtoken library is the most popular JWT implementation for Node.js. It supports both symmetric (HS256) and asymmetric (RS256, ES256) algorithms. The sign() method creates tokens, while verify() validates them. Use environment variables for secret keys and implement proper error handling for token validation.
Sample output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpYXQiOjE2ODAwMDAwMDAsImV4cCI6MTY4MDAwMzYwMCwiaXNzIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20ifQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
JavaScript notes
- Install with
npm install jsonwebtoken(Node.js only); for browsers, edge runtimes and Deno usejose, which runs on Web Crypto. - Pass
algorithms: ['HS256']to everyjwt.verify()call, including the Express middleware. expiresInaccepts seconds or strings like'15m';jwt.decode()does not verify anything.
JWT Code Examples in Python
Generate secure JWT tokens in Python using the PyJWT library. Ideal for Django REST Framework, Flask APIs, FastAPI endpoints, and Python microservices authentication.
import jwt
import datetime
import os
# Secret key (store in environment variables)
SECRET_KEY = os.environ['JWT_SECRET'] # 32+ random bytes, e.g. secrets.token_urlsafe(32)
ISSUER = 'https://yourdomain.com'
AUDIENCE = 'https://yourdomain.com'
ALGORITHM = 'HS256'
# Create token payload
payload = {
'user_id': 123,
'username': 'john_doe',
'role': 'admin',
'iss': ISSUER,
'aud': AUDIENCE,
'iat': datetime.datetime.now(datetime.timezone.utc),
'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)
}
# Generate JWT
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
print(token)
# Output: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
# Decode and verify JWT
try:
decoded = jwt.decode(
token,
SECRET_KEY,
algorithms=[ALGORITHM],
issuer=ISSUER,
audience=AUDIENCE
)
print(decoded)
except jwt.ExpiredSignatureError:
print("Token has expired")
except jwt.InvalidTokenError as e:
print(f"Invalid token: {e}")
# Flask decorator example
from functools import wraps
from flask import request, jsonify
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if not token:
return jsonify({'message': 'Token is missing'}), 401
try:
token = token.split(' ')[1] # Remove "Bearer "
data = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM], issuer=ISSUER, audience=AUDIENCE)
except (IndexError, jwt.InvalidTokenError):
return jsonify({'message': 'Invalid token'}), 403
return f(*args, **kwargs)
return decorated
How it works in Python
PyJWT (pip install PyJWT) encodes datetime values in iat and exp as Unix timestamps. Use timezone-aware times, datetime.datetime.now(datetime.timezone.utc), since utcnow() is deprecated as of Python 3.12. jwt.decode() requires the algorithms list, checks exp automatically and checks iss and aud when you pass them; a token that carries an aud claim is rejected if no audience is given, which is why the Flask decorator passes it too.
Sample output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
Python notes
- Install
PyJWT[crypto](addscryptography) for RS256, ES256 and EdDSA. - Catch
jwt.InvalidTokenError, the base class ofExpiredSignatureErrorandInvalidAudienceError, rather than a bareexcept. - Generate the secret with
secrets.token_urlsafe(32);leeway=60indecode()allows for clock skew.
JWT Code Examples in Java
Generate secure JWT tokens in Java using the JJWT library. Perfect for Spring Boot applications, enterprise microservices, and RESTful API authentication.
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtGenerator {
// Secret key (256 bits for HS256)
private static final String SECRET = "your-256-bit-secret-key-minimum-32-characters";
private static final Key KEY = Keys.hmacShaKeyFor(SECRET.getBytes());
private static final String ISSUER = "https://yourdomain.com";
private static final String AUDIENCE = "https://yourdomain.com";
public static String generateToken(String userId, String username, String role) {
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
Date exp = new Date(nowMillis + 3600000); // 1 hour
// Custom claims
Map<String, Object> claims = new HashMap<>();
claims.put("user_id", userId);
claims.put("username", username);
claims.put("role", role);
return Jwts.builder()
.setClaims(claims)
.setIssuer(ISSUER)
.setAudience(AUDIENCE)
.setIssuedAt(now)
.setExpiration(exp)
.signWith(KEY, SignatureAlgorithm.HS256)
.compact();
}
public static Claims validateToken(String token) {
try {
return Jwts.parserBuilder()
.setSigningKey(KEY)
.requireIssuer(ISSUER)
.requireAudience(AUDIENCE)
.build()
.parseClaimsJws(token)
.getBody();
} catch (JwtException e) {
throw new RuntimeException("Invalid JWT token: " + e.getMessage());
}
}
public static void main(String[] args) {
String token = generateToken("123", "john_doe", "admin");
System.out.println("JWT: " + token);
Claims claims = validateToken(token);
System.out.println("User ID: " + claims.get("user_id"));
}
}
How it works in Java
JJWT (Java JWT) is the most comprehensive JWT library for Java. It provides type-safe builders and parsers with strong security defaults. Use Keys.hmacShaKeyFor() to generate proper signing keys and parserBuilder() for validation with claim verification. The library automatically handles Base64 URL encoding and JSON serialization.
Sample output
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMTIzIiwidXNlcm5hbWUiOiJqb2huX2RvZSIsInJvbGUiOiJhZG1pbiIsImlzcyI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJhdWQiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiaWF0IjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDB9.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
Java notes
- JJWT needs
jjwt-apiplus the runtime modulesjjwt-implandjjwt-jackson(orjjwt-gson). - The example uses the 0.11.x API; 0.12 renames it (
claims(),issuer(),Jwts.parser().verifyWith(key),parseSignedClaims()) and deprecates the old methods. - Use
SECRET.getBytes(StandardCharsets.UTF_8), or better a Base64-decoded random secret, so the key does not depend on the platform charset.
JWT Code Examples in C#
Generate secure JWT tokens in C# using System.IdentityModel.Tokens.Jwt for ASP.NET Core applications. Ideal for Web API authentication, Blazor apps, and microservices authorization.
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
public class JwtGenerator
{
private const string SecretKey = "your-256-bit-secret-key-minimum-32-characters";
private const string Issuer = "https://yourdomain.com";
private const string Audience = "https://yourdomain.com";
public static string GenerateToken(string userId, string username, string role)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim("user_id", userId),
new Claim("username", username),
new Claim("role", role),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public static ClaimsPrincipal ValidateToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(SecretKey);
var validationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Issuer,
ValidAudience = Audience,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
return tokenHandler.ValidateToken(token, validationParameters, out _);
}
public static void Main()
{
string jwt = GenerateToken("123", "john_doe", "admin");
Console.WriteLine($"JWT: {jwt}");
var principal = ValidateToken(jwt);
Console.WriteLine($"User: {principal.FindFirst("username")?.Value}");
}
}
How it works in C#
ASP.NET Core uses System.IdentityModel.Tokens.Jwt for JWT operations. The JwtSecurityToken class represents tokens, while JwtSecurityTokenHandler handles serialization and validation. Use TokenValidationParameters to configure strict validation rules. Always validate issuer, audience, lifetime, and signing key.
Sample output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTIzIiwidXNlcm5hbWUiOiJqb2huX2RvZSIsInJvbGUiOiJhZG1pbiIsImp0aSI6IjEyMzQ1Njc4LTEyMzQtMTIzNC0xMjM0LTEyMzQ1Njc4OTBhYiIsImlzcyI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJhdWQiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiZXhwIjoxNjgwMDAzNjAwfQ.signature
C# notes
JwtSecurityTokenHandleris in theSystem.IdentityModel.Tokens.Jwtpackage; the newerJsonWebTokenHandler(Microsoft.IdentityModel.JsonWebTokens) is faster and is what ASP.NET Core 8 uses by default.- Recent
Microsoft.IdentityModelversions reject HS256 keys shorter than 256 bits. ClockSkewinTokenValidationParametersdefaults to 5 minutes; lower it for short-lived tokens.
JWT Code Examples in C++
Generate secure JWT tokens in C++ using the jwt-cpp library. Suitable for game servers, native desktop applications, and high-performance authentication systems.
#include <jwt-cpp/jwt.h>
#include <iostream>
#include <chrono>
#include <cstdlib>
#include <stdexcept>
std::string generateJWT(const std::string& userId,
const std::string& username,
const std::string& role) {
auto now = std::chrono::system_clock::now();
auto exp = now + std::chrono::hours(1);
const char* env = std::getenv("JWT_SECRET"); // 32+ random bytes
if (!env) throw std::runtime_error("JWT_SECRET is not set");
std::string secret = env;
auto token = jwt::create()
.set_issuer("https://yourdomain.com")
.set_audience("https://yourdomain.com")
.set_issued_at(now)
.set_expires_at(exp)
.set_payload_claim("user_id", jwt::claim(userId))
.set_payload_claim("username", jwt::claim(username))
.set_payload_claim("role", jwt::claim(role))
.sign(jwt::algorithm::hs256{secret});
return token;
}
bool validateJWT(const std::string& token, const std::string& secret) {
try {
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::hs256{secret})
.with_issuer("https://yourdomain.com")
.with_audience("https://yourdomain.com");
auto decoded = jwt::decode(token);
verifier.verify(decoded);
// Access claims
std::cout << "User ID: "
<< decoded.get_payload_claim("user_id").as_string()
<< std::endl;
return true;
} catch (const std::exception& e) {
std::cerr << "Validation failed: " << e.what() << std::endl;
return false;
}
}
int main() {
std::string jwt = generateJWT("123", "john_doe", "admin");
std::cout << "JWT: " << jwt << std::endl;
validateJWT(jwt, std::getenv("JWT_SECRET"));
return 0;
}
How it works in C++
The jwt-cpp library provides a modern C++ interface for JWT operations. It uses a fluent API for token creation and a verifier pattern for validation. The library supports HS256, RS256, and ES256 algorithms. Use std::chrono for time handling and proper exception handling for validation errors.
Sample output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTIzIiwidXNlcm5hbWUiOiJqb2huX2RvZSIsInJvbGUiOiJhZG1pbiIsImlzcyI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJhdWQiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiaWF0IjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDB9.signature
C++ notes
- jwt-cpp is header-only but links against OpenSSL (or LibreSSL or wolfSSL) for the signatures.
jwt::verify()checksexp,nbfandiat;.leeway(60)sets the skew allowance.- Only algorithms passed to
allow_algorithm()are accepted, which pins HS256 as recommended.
JWT Code Examples in Ruby
Generate secure JWT tokens in Ruby using the ruby-jwt gem. Perfect for Rails APIs, Sinatra applications, and Ruby microservices authentication.
require 'jwt'
# Secret key (store in environment variables)
SECRET_KEY = ENV.fetch('JWT_SECRET') # 32+ random bytes, e.g. SecureRandom.hex(32)
ISSUER = 'https://yourdomain.com'
AUDIENCE = 'https://yourdomain.com'
ALGORITHM = 'HS256'
def generate_jwt(user_id:, username:, role:)
payload = {
user_id: user_id,
username: username,
role: role,
iss: ISSUER,
aud: AUDIENCE,
iat: Time.now.to_i,
exp: Time.now.to_i + 3600 # 1 hour
}
JWT.encode(payload, SECRET_KEY, ALGORITHM)
end
def validate_jwt(token)
begin
decoded = JWT.decode(
token,
SECRET_KEY,
true,
{
algorithm: ALGORITHM,
iss: ISSUER,
aud: AUDIENCE,
verify_iss: true,
verify_aud: true,
verify_exp: true
}
)
decoded.first
rescue JWT::ExpiredSignature
puts "Token has expired"
nil
rescue JWT::DecodeError => e
puts "Invalid token: #{e.message}"
nil
end
end
# Generate token
jwt = generate_jwt(user_id: 123, username: 'john_doe', role: 'admin')
puts jwt
# Output: "eyJhbGciOiJIUzI1NiJ9..."
# Validate token
payload = validate_jwt(jwt)
puts payload['username'] if payload
# Rails middleware example
class JwtAuthenticator
def self.call(request)
token = request.headers['Authorization']&.split(' ')&.last
return nil unless token
validate_jwt(token)
end
end
How it works in Ruby
The ruby-jwt gem is the standard JWT library for Ruby applications. It provides simple encode/decode methods with comprehensive validation options. Use JWT.encode to create tokens and JWT.decode with validation options for verification. The gem supports HS256, RS256, and ES256 algorithms.
Sample output
eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlhdCI6MTY4MDAwMDAwMCwiZXhwIjoxNjgwMDAzNjAwfQ.YVPuJ_EqJr8vOT5JkUqHxX9Rj3LmN4K8sQ2TpY6wZ1c
Ruby notes
- Install with
gem install jwt; passalgorithm:toJWT.decodeso only HS256 is accepted. expis verified by default;issandaudonly withverify_iss: trueandverify_aud: true, as in the example.- In Rails, keep the secret in
Rails.application.credentials;JWT::ExpiredSignatureis a subclass ofJWT::DecodeError, so rescue it first.
JWT Code Examples in Go
Generate secure JWT tokens in Go using the golang-jwt library. Idiomatic Go implementation for microservices, REST APIs, and cloud-native authentication.
package main
import (
"fmt"
"os"
"time"
"github.com/golang-jwt/jwt/v5"
)
var secretKey = []byte(os.Getenv("JWT_SECRET")) // 32+ random bytes
type Claims struct {
UserID int `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
func GenerateJWT(userID int, username, role string) (string, error) {
claims := Claims{
UserID: userID,
Username: username,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "https://yourdomain.com",
Audience: jwt.ClaimStrings{"https://yourdomain.com"},
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(secretKey)
}
func ValidateJWT(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
// Validate signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secretKey, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, fmt.Errorf("invalid token")
}
func main() {
// Generate JWT
token, err := GenerateJWT(123, "john_doe", "admin")
if err != nil {
panic(err)
}
fmt.Println("JWT:", token)
// Validate JWT
claims, err := ValidateJWT(token)
if err != nil {
panic(err)
}
fmt.Printf("User: %s (ID: %d)\n", claims.Username, claims.UserID)
}
How it works in Go
The golang-jwt library (formerly dgrijalva/jwt-go) is the standard JWT implementation for Go. It uses type-safe structs for claims and provides strong validation. Always validate the signing method in the key function to prevent algorithm confusion attacks. Use RegisteredClaims for standard JWT claims.
Sample output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoiam9obl9kb2UiLCJyb2xlIjoiYWRtaW4iLCJpc3MiOiJodHRwczovL3lvdXJkb21haW4uY29tIiwiYXVkIjpbImh0dHBzOi8veW91cmRvbWFpbi5jb20iXSwiaWF0IjoxNjgwMDAwMDAwLCJleHAiOjE2ODAwMDM2MDB9.signature
Go notes
- Install with
go get github.com/golang-jwt/jwt/v5; v5 validatesexpandnbfby default. - Instead of the manual method check,
jwt.WithValidMethods([]string{"HS256"})pins the algorithm as a parser option. - Add
jwt.WithIssuer(...)andjwt.WithAudience(...)toParseWithClaims; v5 does not check them otherwise.
Try the Interactive Generator
Need values right now rather than code? The JWT generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE JWT GENERATOR →