我正在使用 spring-security-saml2-service-provider
在我的一个 Spring Boot 应用程序中进行身份验证,并且我正在使用自定义 JwtAuthorizationFilter
(通过http 身份验证 header )在不同的 Spring Boot 应用程序中。
它们各自都能完美工作。
现在我需要编写一个使用它们的 Spring Boot 应用程序。如果 JWT token 可用(身份验证 header ),则使用 JwtAuthorizationFilter
,否则使用 saml2Login
。
SAML2 配置如下所示:(没有过滤器,只有 saml2Login
)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/saml2/service-provider-metadata/**").permitAll()
.antMatchers("/**").authenticated().and()
// use SAML2
.saml2Login()
.addObjectPostProcessor(new ObjectPostProcessor<OpenSamlAuthenticationProvider>() {
public <O extends OpenSamlAuthenticationProvider> O postProcess(O samlAuthProvider) {
samlAuthProvider.setAuthoritiesExtractor(authoritiesExtractor());
samlAuthProvider.setAuthoritiesMapper(authoritiesMapper());
return samlAuthProvider;
}
})
;
}
JWT 配置如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/**").authenticated().and()
// use JWT
.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtUtil))
;
}
我想我需要类似 JwtOrSaml2AuthenticationFilter
的东西,但不知道该怎么做。
最佳答案
解决办法是
- 使用 @Order 复制配置并
在 addFilter 之前设置基于 header 的 requestMatcher
@EnableWebSecurity public class SecurityConfiguration { @Order(100) // lower number = higher priority @Configuration @RequiredArgsConstructor public static class AppSecurityJWT extends WebSecurityConfigurerAdapter { final JWTUtil jwtUtil; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and() .antMatcher("/**").authorizeRequests() .antMatchers("/saml2/service-provider-metadata/**", "/idm-app/**").permitAll() .antMatchers("/**").authenticated().and() // This configuration will only be active if the Authorization header is present in the request .requestMatcher(new RequestHeaderRequestMatcher("Authorization")).addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtUtil)) ; } } @Order(101) @Configuration @RequiredArgsConstructor public static class AppSecuritySAML2 extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and() .antMatcher("/**").authorizeRequests() .antMatchers("/saml2/service-provider-metadata/**", "/idm-app/**").permitAll() .antMatchers("/**").authenticated().and() // This whole configuration will only be active, if the previous (100) didn't match .saml2Login() //... ; } }
关于java - 对于同一路径,JWT 身份验证可回退到 SAML2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61411208/