Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Last active April 11, 2024 10:04
Show Gist options
  • Select an option

  • Save gexiangdong/32f64f6eba6b30c6ed2eb4d0b4faf4ea to your computer and use it in GitHub Desktop.

Select an option

Save gexiangdong/32f64f6eba6b30c6ed2eb4d0b4faf4ea to your computer and use it in GitHub Desktop.
JWT token的生成和解析

创建和解析JWT,可以使用如下依赖:

  <dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.3.0</version>
  </dependency>

创建代码片段:

/** 生成JWT **/
public String createToken(String name, String userId, String email) throws IllegalArgumentException, UnsupportedEncodingException{
    JWTCreator.Builder builder = JWT.create();
    Algorithm algorithm = Algorithm.HMAC256("xxxxx"); //另外一端解析时也需要这个密码
    String token = builder.withClaim("name", name).withClaim("user_id", userId).withClaim("email", email)
                    .withExpiresAt(new Date(new Date().getTime() + 24*3600*1000)).sign(algorithm);
    return token;
}

解析代码片段:

/** 解析JWT **/
public User parseJwt(String token){
    User = new User();
    try {
        Algorithm algorithm = Algorithm.HMAC256("xxxxx"); // 另外一端解析时也需要这个密码
        JWTVerifier verifier = JWT.require(algorithm).acceptExpiresAt(5).build(); // Reusable verifier instance
        DecodedJWT jwt = verifier.verify(token);
        String userId = jwt.getClaim("user_id").asString();
        String name = jwt.getClaim("name").asString();
        String email = jwt.getClaim("email").asString();
        user.setId(userId);
        user.setName(name);
        user.setEmail(email);
    } catch (JWTVerificationException | IllegalArgumentException | UnsupportedEncodingException e) {
        log.error("无效的token" + token, e);
        return null;
    } catch (Throwable e) {
        log.error("验证token异常:" + token, e);
        return null;
    }
    return user;
}

上面是用了相同的密码做的签名,也可以用RSA的公钥私钥。

@coolcoolercool
Copy link

builder.withClaim("name", name.withClaim("user_id", userId)
应该是
builder.withClaim("name", name).withClaim("user_id", userId)
看着是少了括号

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment