Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token 令牌建議不要存放密碼 #71

Open
goseesomething opened this issue Nov 8, 2021 · 1 comment
Open

Token 令牌建議不要存放密碼 #71

goseesomething opened this issue Nov 8, 2021 · 1 comment

Comments

@goseesomething
Copy link

我是去了Udemy看了別人課程security+jwt 再來這邊造訪
因為剛好再需要整合多一層 shiro
也很感謝大大願意分享你的編寫思路
並略為修改了大大的JWTUtil部份
將 jwtSecret 取代為密碼 並保存在 Spring resources application
並再加入多一次驗證 username是否與token內的username一樣
而jwtExpirationInMs 也是保存在Spring resources application 方便後續修改

public static boolean verify(String token, String username) {
try {
Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
JWTVerifier verifier = JWT.require(algorithm)
.withClaim("username", username)
.build();
DecodedJWT decodeJWT = verifier.verify(token);

    // verify username
    String username_in_token = decodeJWT.getClaim("username").asString();

    if (! username_in_token.equals(username)) {
        throw new APIException("username doesn't match token", HttpStatus.UNAUTHORIZED);
    }

    // verification passed
    return true;

}  catch (TokenExpiredException e) {
    throw new APIException("token is expired", HttpStatus.UNAUTHORIZED);

}   catch (Exception exception) {
    throw new APIException("unknown exception has been raised", HttpStatus.UNAUTHORIZED);
}

}

public static String sign(String username) {
try {
Date current_date = new Date(System.currentTimeMillis());
Date expire_date = new Date(System.currentTimeMillis() + jwtExpirationInMs);
Algorithm algorithm = Algorithm.HMAC256(jwtSecret);

    String token = JWT.create()
            .withClaim("username", username)
            .withIssuedAt(current_date) // Assign Datetime
            .withExpiresAt(expire_date)  // Expire Datetime
            .withClaim("username", username) // Attach username to verify
            .sign(algorithm);

    return token;

} catch (UnsupportedEncodingException e) {
    return null;
}

}

@Smith-Cruise
Copy link
Owner

谢谢,不过这个项目我已经没工夫研究了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants