DevToolsForYou

JWT Encoder and Decoder in Java — Code Examples

JWT Encoder and Decoder in JavaUse the online tool →

JSON Web Tokens (JWTs) are a compact, URL-safe format for transmitting claims between parties. A JWT has three Base64url-encoded parts separated by dots: header, payload, and signature. Here is how to sign, verify, and decode JWTs in each language.

JJWT (io.jsonwebtoken) is the most popular Java JWT library. Use Jwts.builder() to create tokens and Jwts.parser() to verify them.

Java (JJWT 0.12+)
// Maven:
// io.jsonwebtoken:jjwt-api:0.12.5
// io.jsonwebtoken:jjwt-impl:0.12.5 (runtime)
// io.jsonwebtoken:jjwt-jackson:0.12.5 (runtime)
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;

public class JwtExample {
    public static void main(String[] args) {
        SecretKey key = Keys.hmacShaKeyFor(
            "my-secret-key-32-bytes-long!!!!!".getBytes());

        // Sign (encode)
        String token = Jwts.builder()
            .claim("userId", 42)
            .claim("name", "Alice")
            .claim("role", "admin")
            .issuedAt(new Date())
            .expiration(new Date(System.currentTimeMillis() + 3_600_000))
            .signWith(key)
            .compact();
        System.out.println(token);

        // Verify and decode
        try {
            Claims claims = Jwts.parser()
                .verifyWith(key).build()
                .parseSignedClaims(token).getPayload();
            System.out.println(claims.get("name"));             // Alice
            System.out.println(claims.get("userId", Integer.class)); // 42
        } catch (JwtException e) {
            System.out.println("Invalid token: " + e.getMessage());
        }
    }
}
Notes & gotchas
  • Keys.hmacShaKeyFor requires at least 256 bits (32 bytes) for HS256 — use a longer secret in production.
  • Catch JwtException (or its subtypes ExpiredJwtException, SignatureException) to handle token errors gracefully.
  • For RS256, use Keys.keyPairFor(SignatureAlgorithm.RS256) or load PEM keys with the JJWT PKCS8 helpers.
Try it in your browser

Need to jwt encode/decode without writing code? The JWT Encoder and Decoder runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JWT Encode/Decode
JWT Encoder and Decoder in other languages