fix(鉴权): JWT 解析拆三态——过期但签名有效从此可与伪造区分
ExpiredJwtException 必须先于通用 JwtException 捕获,否则被后一个 catch 吞掉、三态恒退回两态。 parse() 保持过期→null 原语义(requireUser / currentDeviceId / checkLogin 三处消费者按 null 判), 本批 73 例含这三处既有测试全绿。
This commit is contained in:
@@ -98,19 +98,73 @@ public class JwtService {
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parse(String token) {
|
||||
public enum Verdict { VALID, EXPIRED_SIGNED, INVALID }
|
||||
|
||||
/**
|
||||
* 三态解析结果。此前 {@link #parse(String)} 只回「能用 / null」,于是"签名有效但已过期"
|
||||
* 与"签名对不上"在调用方是同一个读数——而会话容忍只需要前者。
|
||||
*/
|
||||
public static final class ParseResult {
|
||||
private final Verdict verdict;
|
||||
private final Claims claims;
|
||||
|
||||
ParseResult(Verdict verdict, Claims claims) {
|
||||
this.verdict = verdict;
|
||||
this.claims = claims;
|
||||
}
|
||||
|
||||
public Verdict verdict() {
|
||||
return verdict;
|
||||
}
|
||||
|
||||
public Claims claims() {
|
||||
return claims;
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return verdict == Verdict.VALID;
|
||||
}
|
||||
|
||||
public boolean isExpiredSigned() {
|
||||
return verdict == Verdict.EXPIRED_SIGNED;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 过期与伪造必须分家:{@code ExpiredJwtException} 要在通用 {@code JwtException} 之前捕获,
|
||||
* 否则被后一个 catch 整段吞掉,三态永远读不出 EXPIRED_SIGNED(恒等于今天的两态)。
|
||||
* jj 先验签再校验 exp,故过期分支里的 {@code e.getClaims()} 是签名有效的那份 claims。
|
||||
*/
|
||||
public ParseResult parseWithVerdict(String token) {
|
||||
try {
|
||||
return Jwts.parser()
|
||||
Claims claims = Jwts.parser()
|
||||
.verifyWith(signingKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
return new ParseResult(Verdict.VALID, claims);
|
||||
} catch (io.jsonwebtoken.ExpiredJwtException e) {
|
||||
return new ParseResult(Verdict.EXPIRED_SIGNED, e.getClaims());
|
||||
} catch (JwtException | IllegalArgumentException e) {
|
||||
log.debug("[auth] jwt parse failed: {}", e.getMessage());
|
||||
return null;
|
||||
return new ParseResult(Verdict.INVALID, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 语义与改造前逐字一致:过期令牌照样回 null。三处消费者
|
||||
* (requireUser、currentDeviceId、checkLogin)都按 null 判,不许被本次改造改变行为。
|
||||
*/
|
||||
public Claims parse(String token) {
|
||||
ParseResult result = parseWithVerdict(token);
|
||||
return result.isValid() ? result.claims() : null;
|
||||
}
|
||||
|
||||
/** 仅供用例签发过期令牌(生产代码不许调)。 */
|
||||
SecretKey signingKeyForTest() {
|
||||
return signingKey();
|
||||
}
|
||||
|
||||
public long ttlSeconds() {
|
||||
return Duration.ofHours(props.getJwtTtlHours()).toSeconds();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user