Spring Boot中获取JWT自定义声明失败的技术求助
Spring Boot中JWT自定义声明获取失败的解决方法
你当前能通过方法引用Claims::getSubject成功获取JWT的subject,是因为getSubject()是无参方法,符合Function<Claims, T>的函数式接口要求。但Claims.get(String)是带参数的方法,直接用Claims::get("name of the token")这种写法是错误的——方法引用无法传递参数,必须用lambda表达式来包装带参调用。
正确的自定义声明提取代码
修改你的提取方法,用lambda表达式替代错误的方法引用:
public String extractCustomClaim(String token) { return extractClaim(token, claims -> claims.get("name of the token")); }
如果需要更通用的自定义声明提取方法,可以写一个带参数的版本,适配不同的声明键:
public <T> T extractCustomClaim(String token, String claimKey) { return extractClaim(token, claims -> claims.get(claimKey)); }
补充说明
- 确保你的JWT令牌在生成时确实包含了名为
"name of the token"的自定义声明,否则get()方法会返回null - 如果自定义声明是特定类型(比如Integer、Boolean),可以用
claims.get(claimKey, Class<T>)来直接获取对应类型,避免强制类型转换:
public Integer extractIntegerClaim(String token, String claimKey) { return extractClaim(token, claims -> claims.get(claimKey, Integer.class)); }
内容的提问来源于stack exchange,提问作者Klaus Friman
相关产品推荐
相关产品推荐

