Аутентификация JWT с откатом к SAML2 по тому же пути - PullRequest
0 голосов
/ 24 апреля 2020

Я использую spring-security-saml2-service-provider для аутентификации в одном из моих приложений весенней загрузки, и я использую пользовательский JwtAuthorizationFilter (через заголовок http Authentication) в другом приложении весенней загрузки.

Они оба прекрасно работают самостоятельно.

Теперь мне нужно написать приложение с загрузочной пружиной, которое использует оба из них. Если токен JWT доступен (заголовок аутентификации), используйте 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 но не знаю как это сделать.

1 Ответ

0 голосов
/ 25 апреля 2020

Решение состоит в том, чтобы

  1. Дублировать конфигурацию с помощью @Order и
  2. Установить запрос заголовка на основе заголовка перед addFilter

    @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()
                    //...
            ;
        }
    }
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...