Skip to content

Instantly share code, notes, and snippets.

@dsdstudio
Created November 30, 2019 06:53
Show Gist options
  • Save dsdstudio/aa8ecf47290c9f85c7fb7894867db4c1 to your computer and use it in GitHub Desktop.
Save dsdstudio/aa8ecf47290c9f85c7fb7894867db4c1 to your computer and use it in GitHub Desktop.

Revisions

  1. dsdstudio created this gist Nov 30, 2019.
    46 changes: 46 additions & 0 deletions jwt.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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);
    }
    }