npm install --save express body-parser jsonwebtoken
const jwt = require('jsonwebtoken');
writing...
https://mvnrepository.com/artifact/com.auth0/java-jwt
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;
}
}