Spring Boot3 OAuth2资源服务器自定义Principal在权限注解中使用方案
Spring Boot 3 OAuth2资源服务器自定义Principal实现
实现方案
Spring Security提供了直接的配置方式实现需求,核心是通过自定义JwtAuthenticationConverter将JWT转换为你的MyPrincipal实例,同时支持SpEL表达式中的属性访问。
步骤说明
定义自定义Principal相关类(你已完成部分)
- 确保
MyPrincipal接口和JwtPrincipal实现类正确:public interface MyPrincipal { Integer getId(); } public class JwtPrincipal implements MyPrincipal { private final Integer id; public JwtPrincipal(Jwt jwt) { this.id = Integer.parseInt(jwt.getClaim("id")); } @Override public Integer getId() { return id; } } - 定义转换器函数式接口:
@FunctionalInterface public interface JwtPrincipalConverter { MyPrincipal convert(Jwt jwt); }
- 确保
配置自定义JwtAuthenticationConverter
注册JwtAuthenticationConverterBean,将你的JwtPrincipalConverter设置为principal转换器:@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public JwtPrincipalConverter jwtPrincipalConverter() { return JwtPrincipal::new; } @Bean public JwtAuthenticationConverter jwtAuthenticationConverter(JwtPrincipalConverter principalConverter) { JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); // 设置自定义Principal转换器 converter.setPrincipalConverter(principalConverter::convert); return converter; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt // 应用自定义的转换器 .jwtAuthenticationConverter(jwtAuthenticationConverter(jwtPrincipalConverter())) ) ); return http.build(); } }
效果验证
完成配置后,即可实现你需要的功能:
- 控制器中直接注入自定义Principal:
@PreAuthorize("principal.id == 100") @GetMapping public MyPrincipal test(@AuthenticationPrincipal MyPrincipal principal) { return principal; } - SpEL表达式
principal.id == 100可直接访问自定义Principal的属性(SpEL会自动映射到getId()方法)
原理说明
默认情况下,Spring Security OAuth2资源服务器会将JWT对象作为JwtAuthenticationToken的principal。通过自定义JwtAuthenticationConverter的principalConverter,我们将JWT转换为自定义的MyPrincipal实例,这样无论在控制器注入还是方法权限表达式中,操作的都是自定义Principal对象,自然支持直接访问其属性。
内容的提问来源于stack exchange,提问作者Alexander Vlasov
相关产品推荐
相关产品推荐

