我使用Nextjs主要用于我的前端,使用Java springboot引导我的后端。但是,我想使用nextjs中间件来通过JWT保护我的路由。由于jsonwebtoken不能在边缘函数上运行,所以我使用的是jose。
在尝试从cookie中获取JWT之后,我尝试验证它并获得以下消息:
JWSSignatureVerificationFailed:签名验证失败
这里是我的令牌在春季后端的签名:
public static String generateJwtToken(AppUser user) {
Map<String, Object> claims = new HashMap<>();
return Jwts.builder()
.setClaims(claims)
.setSubject(user.getUsername())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + TOKEN_VALIDITY * 1000))
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}下面是在我的nextjs中间件文件中验证它的尝试:
const token = request.cookies.get('jwt');
const { payload } = await jwtVerify(
token,
new TextEncoder().encode(process.env.SECRET_KEY)
);注意: jwtSecret和SECRET_KEY是来自同一个.env文件的完全相同的值。任何帮助都将不胜感激。
发布于 2022-10-22 23:38:53
我在这里或多或少找到了答案,https://github.com/auth0/node-jsonwebtoken/issues/208#issuecomment-231861138。这个精确的注释解释了秘密密钥应该发生什么。
至于我在代码中修正的内容,我必须以字节数组的形式返回密钥。
.signWith(SignatureAlgorithm.HS512, jwtSecret.getBytes("UTF-8"))https://stackoverflow.com/questions/74167226
复制相似问题