java jwt example

java

In Java, you can use the jjwt library to work with JSON Web Tokens (JWTs). Here’s an example of how you can use jjwt to create and verify a JWT:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class Main {
  public static void main(String[] args) {
    // Set up the JWT
    String secret = "my-secret-key";
    String jwt = Jwts.builder()
                     .setSubject("user1")
                     .setIssuer("my-app")
                     .signWith(SignatureAlgorithm.HS256, secret)
                     .compact();
    System.out.println(jwt);

    // Verify the JWT
    Jwts.parser().setSigningKey(secret).parseClaimsJws(jwt);
  }
}

This code will create a JWT with the subject “user1” and the issuer “my-app”, and sign it using the HMAC-SHA256 algorithm and the secret key “my-secret-key”. It will then print the JWT, and finally verify the JWT by parsing it and checking the signature.

Note that in a real application, you should use a more secure key for signing the JWT, such as one that is generated using a key derivation function like PBKDF2. You should also make sure to use a unique secret key for each JWT, and keep the key secret.