Created
November 30, 2019 06:53
-
-
Save dsdstudio/aa8ecf47290c9f85c7fb7894867db4c1 to your computer and use it in GitHub Desktop.
jwt token create and validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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