Make a note of the introduction of JWT using the Java library.
--The abbreviation for Web Token is "URL Safe Token including JSON that can be signed". --JWT is composed of Header, Payload, and Signature, and Header and Payload are Base64-encoded information of Json, so it seems better not to put anything that you do not want to disclose to the outside, such as user information and password. --Since it is signed, you can check it at the time of verification even if you tamper with the Json part.
――The whole token looks like this
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.izVguZPRsBQ5Rqw6dhMvcIwy8_9lQnrO3vpxGwPCuzs
--Header part
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
--When you decode the Header
{"typ":"JWT","alg":"HS256"}
--Payload part
eyJpc3MiOiJhdXRoMCJ9
--When you decode Payload
{"iss":"auth0"}
--Environment - java8 --java-jwt (java library that handles jwt that is also published on jwt.io) --This time, I made a JWT with Issuer and Expire Time and confirmed the operation. --The algorithm uses HS256 --Token generation
try {
Date expireTime = new Date();
expireTime.setTime(expireTime.getTime() + 600000l);
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
.withIssuer("auth0")
.withExpiresAt(expireTime)
.sign(algorithm);
} catch (JWTCreationException exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
--Token verification
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.izVguZPRsBQ5Rqw6dhMvcIwy8_9lQnrO3vpxGwPCuzs";
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
--If you borrow the code written on the official page of java-jwt, you can easily check the operation.
--When the Json part (Header and Payload part) is tampered with, JWTVerificationException
is thrown and checked.
Recommended Posts