項目先後端分離,請求認證使用的是JWT無狀態認證。最近遇到一個問題,認證token須要從token中獲取用戶名,可是這個token有多是過時的。通常取得用戶名用的是下面的代碼。java
private Claims getClaimsFromToken(String token) {
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
}
複製代碼
若是token沒有過時,則能夠經過Claims.getSubject()得到用戶名。可是token過時,則會拋出ExpiredJwtException異常,致使沒法獲取用戶名。後端
查看ExpiredJwtException異常,會發現它的父類ClaimJwtException封裝了Claims類成員。因此只要調用getClaims()方法就能夠取得Claim對象,進而取得用戶名。前後端分離
public abstract class ClaimJwtException extends JwtException {
public static final String INCORRECT_EXPECTED_CLAIM_MESSAGE_TEMPLATE = "Expected %s claim to be: %s, but was: %s.";
public static final String MISSING_EXPECTED_CLAIM_MESSAGE_TEMPLATE = "Expected %s claim to be: %s, but was not present in the JWT claims.";
private final Header header;
private final Claims claims;
protected ClaimJwtException(Header header, Claims claims, String message) {
super(message);
this.header = header;
this.claims = claims;
}
protected ClaimJwtException(Header header, Claims claims, String message, Throwable cause) {
super(message, cause);
this.header = header;
this.claims = claims;
}
public Claims getClaims() {
return this.claims;
}
public Header getHeader() {
return this.header;
}
}
複製代碼
取得用戶名的代碼以下。this
/** * 從token中獲取用戶名 */
public String getUsernameFromToken(String token) {
try {
return getClaimsFromToken(token).getSubject();
} catch (ExpiredJwtException e) {
// 過時則從ExpiredJwtException中取username
return e.getClaims().getSubject();
}
}
複製代碼