Skip to content

Instantly share code, notes, and snippets.

@hongry18
Last active June 27, 2017 07:12
Show Gist options
  • Save hongry18/a60cec8e7b6bab020889e295f8a638ce to your computer and use it in GitHub Desktop.
Save hongry18/a60cec8e7b6bab020889e295f8a638ce to your computer and use it in GitHub Desktop.
java jwt sample

JWT Sample

reference

https://jwt.io

nodeJS

dependency (npm)

npm install --save express body-parser jsonwebtoken

sample

const jwt = require('jsonwebtoken');

writing...

java

dependency (maven)

https://mvnrepository.com/artifact/com.auth0/java-jwt

sample

import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class jwtTest {
    
    private String issuer = "auth0";
    private String passphrase = "secret";
    
    public static void main(String[] ar) {
        jwtTest jTest = new jwtTest();
        // generate token
        String token = jTest.generateToken();
        System.out.println(token);
        DecodedJWT jwt = jTest.decodeToken(token);
        
        // bool
        System.out.println(jwt.getClaim("bool").asBoolean());
        // int
        System.out.println(jwt.getClaim("int").asInt());
        // string
        System.out.println(jwt.getClaim("str").asString());
        
        System.out.println(jwt.getIssuer());
        System.out.println(jwt.getExpiresAt());
    }
    
    public String generateToken() {
     // 10 minute
        int expireTime = 10 * 60 * 1000;
        
        Date exp = new Date(System.currentTimeMillis() + expireTime);
        String token = null;
        try {
            Algorithm algorithmHS = Algorithm.HMAC256(passphrase);
            token = JWT.create()
                    .withIssuer(issuer)
                    .withExpiresAt(exp)
                    .withClaim("bool", true)
                    .withClaim("int", 1)
                    .withClaim("str", "str")
                    .sign(algorithmHS);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return token;
    }
    
    public DecodedJWT decodeToken(String token) {
        DecodedJWT jwt = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(passphrase);
            JWTVerifier verifier = JWT.require(algorithm)
                .withIssuer(issuer)
                .build();
            jwt = verifier.verify(token);
        } catch (UnsupportedEncodingException e){
            //UTF-8 encoding not supported
            e.printStackTrace();
        } catch (TokenExpiredException e) {
            System.out.println("The Token has expired");
        } catch (SignatureVerificationException e) {
            System.out.println("The Token's Signature resulted invalid when verified using the Algorithm: HmacSHA256");
        } catch (JWTVerificationException e){
            //Invalid signature/claims
            e.printStackTrace();
        }
        
        return jwt;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment