Spring Boot OAuth2资源服务器如何从SecurityContextHolder获取JWT
1. 原生JWT直接获取(无需修改现有配置)
Spring Security 5.4+ 的OAuth2资源服务器,在JWT认证通过后,会自动将JwtAuthenticationToken存入SecurityContextHolder,不需要额外扩展转换器即可直接取到完整JWT对象。
默认情况下JwtAuthenticationConverter会将JWT的sub声明作为principal,直接拿到的是字符串类型的用户ID。
直接在任意请求线程内执行以下代码即可获取:
// 从SecurityContext获取已认证的Authentication对象 Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth instanceof JwtAuthenticationToken jwtAuth) { // 直接获取原生Jwt对象 Jwt jwt = jwtAuth.getToken(); // 提取任意JWT声明,例如: String userId = jwt.getClaimAsString("sub"); String userEmail = jwt.getClaimAsString("email"); List<String> groups = jwt.getClaimAsStringList("entGrps"); }
注意:
SecurityContextHolder默认基于ThreadLocal实现,仅能在当前请求线程内获取值,异步场景需单独配置上下文传递策略。
2. 自定义用户信息存入Principal(无需手动解析JWT)
如果不想每次都从Jwt对象中提取声明,希望直接从Authentication的principal属性拿到组装好的用户信息,只需要扩展你现有配置里的JwtAuthenticationConverter即可。
步骤1:定义自定义用户载体(按需调整字段)
@Data @AllArgsConstructor public class LoginUser { private String userId; private String username; private List<String> roles; }
步骤2:扩展默认JWT认证转换器
继承JwtAuthenticationConverter,重写getPrincipal方法,将从JWT声明中提取的字段组装为自定义对象:
public class CustomJwtAuthenticationConverter extends JwtAuthenticationConverter { @Override protected Object getPrincipal(Jwt jwt) { // 按需从JWT声明中提取字段 String userId = jwt.getClaimAsString("sub"); String username = jwt.getClaimAsString("preferred_username"); List<String> roles = jwt.getClaimAsStringList("entGrps"); // 返回自定义用户对象,后续直接作为principal使用 return new LoginUser(userId, username, roles); } }
步骤3:修改现有安全配置
将你原配置中的JwtAuthenticationConverter替换为自定义实现,原有权限解析逻辑完全保留:
private JwtAuthenticationConverter jwtAuthenticationConverter() { // 原有权限转换逻辑保持不变 JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter(); authoritiesConverter.setAuthoritiesClaimName("entGrps"); authoritiesConverter.setAuthorityPrefix("ROLE_"); // 替换为自定义的转换器 CustomJwtAuthenticationConverter converter = new CustomJwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter); return converter; }
步骤4:直接从SecurityContext获取自定义用户
配置完成后,无需解析JWT,直接从principal中获取自定义用户对象:
LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String userId = user.getUserId();
配置说明
你现有代码中的JwtDecoder和权限转换逻辑完全适配Spring Security 5.4.2版本,没有兼容问题,不需要额外添加其他过滤器或配置项,JWT认证完成后会自动将Authentication存入SecurityContext。
内容的提问来源于stack exchange,提问作者Mejmo

