我使用了next-auth生成了jwt token,并设置了AUTH_SECRET=123456
,如下所示:
callbacks: {
// Ref: https://authjs.dev/guides/basics/role-based-access-control#persisting-the-role
async jwt({token, user}) {
return token
},
// If you want to use the role in client components
async session({session,user, token}) {
return session
},
}
这是生成的jwt token
eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoib0Y4SU1ycV9sZUxRYXhSeVZnZVNsUXc4VFNabnRrd1R0NmZ1bnZ1ZzhBT2gtR2J1Wkp4dnhHRllQb3FUaVYtRl92YzAtWGxQUjdaRlRLdkVON181VHcifQ..DiXTEIywelVgcF5MuHYlQQ.TscvRH0uxEwyDfJ5g2sN_81ivsFsxPA5FfydYCfw8w_n-qmyH3nBKLp1COg1Vbo2vbyPSnoRmsFDI6nXzZYO264rvqsCAZdmrZL1LF-HLDTUxuPy8KUgiG828P1TPeipX8huemr_h6Yk7MwgMFdqW7dTZbReYvfa-mtSMYkq_10gIgjGLHfd-YZR7En_-77GqXoaryLUOaiZxGe8iya3TMbyTDs9sgN55CvVnRdYcAK6Gy4ptLMiKw0pINdSICgYZhYhjYRfB1VCHzVmjwZeLxpWrWbJgN52tWmfc3xiOwbVsFsYfvR0znt6mvDQw5lNYtDQ-tvUCDwWm-Xdrra5gw.bwAf05t99YvB1QyBgBFVpik9T_Zup2Yq5XuG26h7Qng
但是我使用java 解析的时候报错,如何解决?
static void me() {
String jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoib0Y4SU1ycV9sZUxRYXhSeVZnZVNsUXc4VFNabnRrd1R0NmZ1bnZ1ZzhBT2gtR2J1Wkp4dnhHRllQb3FUaVYtRl92YzAtWGxQUjdaRlRLdkVON181VHcifQ..DiXTEIywelVgcF5MuHYlQQ.TscvRH0uxEwyDfJ5g2sN_81ivsFsxPA5FfydYCfw8w_n-qmyH3nBKLp1COg1Vbo2vbyPSnoRmsFDI6nXzZYO264rvqsCAZdmrZL1LF-HLDTUxuPy8KUgiG828P1TPeipX8huemr_h6Yk7MwgMFdqW7dTZbReYvfa-mtSMYkq_10gIgjGLHfd-YZR7En_-77GqXoaryLUOaiZxGe8iya3TMbyTDs9sgN55CvVnRdYcAK6Gy4ptLMiKw0pINdSICgYZhYhjYRfB1VCHzVmjwZeLxpWrWbJgN52tWmfc3xiOwbVsFsYfvR0znt6mvDQw5lNYtDQ-tvUCDwWm-Xdrra5gw.bwAf05t99YvB1QyBgBFVpik9T_Zup2Yq5XuG26h7Qng";
try {
// 配置JWT解析器,设置签名密钥和允许的算法
Claims claims = Jwts.parserBuilder()
.setSigningKey("123456") // 设置签名密钥
.setAllowedClockSkewSeconds(60) // 允许的时间偏差(可选)
.build()
.parseClaimsJws(jwt) // 解析token,并自动验证签名
.getBody(); // 获取Claims对象
// 从Claims对象中获取你需要的信息
String subject = claims.getSubject();
// ... 获取其他claim信息
System.out.println("Subject: " + subject);
// ... 打印其他信息
} catch (Exception e) {
// 处理异常,可能是签名无效、token过期或其他问题
e.printStackTrace();
}
}
报错信息:
io.jsonwebtoken.MalformedJwtException: JWT strings must contain exactly 2 period characters. Found: 4
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:296)
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:550)
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:610)
at io.jsonwebtoken.impl.ImmutableJwtParser.parseClaimsJws(ImmutableJwtParser.java:173)
at com.seaurl.gatewaysvr.GatewayServerApplication.me(GatewayServerApplication.java:32)
at com.seaurl.gatewaysvr.GatewayServerApplication.main(GatewayServerApplication.java:49)
解决了,next-auth贡献者说了,next-auth生成的token是加过密的,所以仅供当前app使用,如果想要加第三方的token则在登录之后在session中设置一下即可,如:session.accessToken=your token