Open
Description
我是去了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;
}
}
Metadata
Metadata
Assignees
Labels
No labels