signWith(SignatureAlgorithm alg, Key key)
已表示反对。我们应该使用signWith(Key, SignatureAlgorithm)
代替。但我们该怎么做呢。换个位置?
如何按以下方式更改原始代码以使用正确的方法?
public class JwtUtil {
public static final long JWT_TTL = 60 * 60 * 1000L * 24 * 14;
public static final String JWT_KEY = "JSDFSDFSDFASJDHASDASDdfa32dJHASFDA67765asda123dsdsw";
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public static String createJWT(String subject) {
JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
return builder.compact();
}
private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
SecretKey secretKey = generalKey();
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
if (ttlMillis == null) {
ttlMillis = JwtUtil.JWT_TTL;
}
long expMillis = nowMillis + ttlMillis;
Date expDate = new Date(expMillis);
return Jwts.builder()
.setId(uuid)
.setSubject(subject)
.setIssuer("sg")
.setIssuedAt(now)
.signWith(signatureAlgorithm, secretKey)
.setExpiration(expDate);
}
public static SecretKey generalKey() {
byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
return new SecretKeySpec(encodeKey, 0, encodeKey.length, "HmacSHA256");
}
public static Claims parseJWT(String jwt) throws Exception {
SecretKey secretKey = generalKey();
return Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(jwt)
.getBody();
}
}
我注意到它的密钥文档是不同的。不推荐的是key – the algorithm-specific signing key to use to digitally sign the JWT.
,另一个是key – the signing key to use to digitally sign the JWT.
所以我认为key
是不同的。但我不知道怎么调整我的代码。
发布于 2022-08-11 21:38:44
由于不推荐使用signWith(SignatureAlgorithm,SecretKey),所以可以使用signWith(SecretKey)或signWith(SecretKey,SignatureAlgorithm)。
当使用HMAC-SHA时,确保提供的密钥至少与算法的签名相同。
私有静态JwtBuilder getJwtBuilder( subject,Long ttlMillis,String ){。。。SecretKey secretKey = generalKey();返回Jwts.builder() .setId(uuid) .setSubject(subject) .setIssuer("sg") .setIssuedAt(now) .signWith( SecretKey ) //签名算法是根据密钥.setExpiration(ExpDate)的大小选择的;返回Keys.hmacShaKeyFor(encodeKey);}
另外,添加以下依赖项:
对于Maven:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
对于Gradle:
dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtime 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'
}
https://stackoverflow.com/questions/73208128
复制相似问题