Skip to content

Instantly share code, notes, and snippets.

@dsdstudio

dsdstudio/jwt.java

Created Nov 30, 2019
Embed
What would you like to do?
jwt token create and validation
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
class Scratch {
static String createToken() {
try {
Algorithm algorithm = Algorithm.HMAC256("bO4Tbmfhkztt5Ew6hcpZ_jHj56DT4-0SRIKRUYxwYF");
Date expireDate = Date.from(LocalDateTime.now().plusDays(1)
.atZone(ZoneId.systemDefault()).toInstant());
return JWT.create()
.withIssuer("gms")
.withExpiresAt(expireDate)
.withClaim("userId", "20xxxxx")
.withClaim("loginId", "sampleuser")
.sign(algorithm);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void verify(String token) {
Algorithm algorithm = Algorithm.HMAC256("bO4Tbmfhkztt5Ew6hcpZ_jHj56DT4-0SRIKRUYxwYF");
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("gms")
// .acceptExpiresAt(60 * 60 * 24) // expire 1일전부터만 유효
.build();
DecodedJWT decodedJWT = verifier.verify(token);
System.out.println(decodedJWT);
System.out.println("userId -> " + decodedJWT.getClaim("userId").asString());
}
public static void main(String[] args) {
String token = createToken();
System.out.println(token);
verify(token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment