Skip to content

Commit

Permalink
fix: token provider
Browse files Browse the repository at this point in the history
  • Loading branch information
nekolr committed Dec 28, 2023
1 parent b3b15a4 commit 79cf6e9
Showing 1 changed file with 7 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,30 +29,20 @@ public String createToken(String username) {
Date expireDate = new Date(now + period.toMillis());

return Jwts.builder()
.setSubject(username)
.signWith(secretKey, SignatureAlgorithm.HS256)
.setId(UUID.randomUUID().toString().replaceAll("-", ""))
.setExpiration(expireDate)
.subject(username)
.signWith(secretKey, Jwts.SIG.HS256)
.id(UUID.randomUUID().toString().replaceAll("-", ""))
.expiration(expireDate)
.compact();
}

public String getUsername(String token) {
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token)
.getBody();

return claims.getSubject();
}

public Claims getClaims(String token) {
try {
return Jwts.parser()
.setSigningKey(secretKey)
.verifyWith(secretKey)
.build()
.parseClaimsJws(token)
.getBody();
.parseSignedClaims(token)
.getPayload();
} catch (ExpiredJwtException e) {
// token 过期
log.error("Token has expired: {}", e.getMessage());
Expand All @@ -74,33 +64,4 @@ public Claims getClaims(String token) {
}
return null;
}

public boolean validateToken(String token) {
try {
Jwts.parser()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(token);
return true;
} catch (ExpiredJwtException e) {
// token 过期
log.error("Token has expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
// token 格式错误
log.error("Token format error: {}", e.getMessage());
} catch (MalformedJwtException e) {
// token 构造错误
log.error("Token construct error: {}", e.getMessage());
} catch (SignatureException e) {
// 签名失败
log.error("Signature failed: {}", e.getMessage());
} catch (IllegalArgumentException e) {
// 非法参数
log.error("Illegal argument: {}", e.getMessage());
} catch (JwtException e) {
// 其他异常
log.error("Other exception: {}", e.getMessage());
}
return false;
}
}

0 comments on commit 79cf6e9

Please sign in to comment.