You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:03:36