Как реализовать множественную аутентификацию с общим секретом в приложении Spring BootJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Как реализовать множественную аутентификацию с общим секретом в приложении Spring Boot

Сообщение Anonymous »


Я использую RequestHeaderAuthenticationFilter SpringSecurity для аутентификации пользователей. У меня есть собственный AuthenticationProvider, то есть DmpAuthenticationProvider, в библиотеке, которую я импортировал в свой проект. Все работает гладко.

На этом этапе я хочу добавить еще один RequestHeaderAuthenticationFilter, который ищет другой заголовок и аутентифицирует его, используя другой пользовательский AuthenticationProvider

Я видел видео с JavaBrains, Кошик объяснил, что в одном проекте может быть несколько AuthenticationProvider. Я искал, но не смог найти никакой помощи. В статье на веб-сайте Baeldung объясняется метод, но я не использую ни OAuth, ни BasicAuth и не отказываюсь от обычного процесса аутентификации, поэтому у меня он не работает.

Кто-нибудь может мне помочь?

Конфигурация безопасности:

import com.evampsaanga.user.auth.library.config.DelegatedAuthenticationEntryPoint; импортировать com.evampsaanga.user.auth.library.security.DmpAuthenticationProvider; импортировать com.evampsaanga.user.auth.library.util.Private; импортировать org.springframework.beans.factory.annotation.Autowired; импортировать org.springframework.context.annotation.Bean; импортировать org.springframework.context.annotation.Configuration; импортировать org.springframework.security.authentication.AuthenticationManager; импортировать org.springframework.security.authentication.ProviderManager; импортировать org.springframework.security.config.Customizer; импортировать org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; импортировать org.springframework.security.config.annotation.web.builders.HttpSecurity; импортировать org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; импортировать org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; импортировать org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer; импортировать org.springframework.security.config.annotation.web.configurers.HttpBasicConfigurer; импортировать org.springframework.security.config.annotation.web.configurers.LogoutConfigurer; импортировать org.springframework.security.config.http.SessionCreationPolicy; импортировать org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; импортировать org.springframework.security.crypto.password.PasswordEncoder; импортировать org.springframework.security.web.SecurityFilterChain; импортировать org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter; импортировать org.springframework.security.web.header.HeaderWriterFilter; импортировать org.springframework.security.web.util.matcher.AntPathRequestMatcher; импортировать org.springframework.web.cors.CorsConfiguration; импортировать org.springframework.web.cors.CorsConfigurationSource; импортировать org.springframework.web.cors.UrlBasedCorsConfigurationSource; импортировать java.util.Collections; импортировать java.util.List; @Конфигурация @EnableWebSecurity @EnableMethodSecurity общественный класс SecurityConfig { @Autowired частный DmpAuthenticationProvider dmpAuthenticationProvider; @Autowired частная DelegatedAuthenticationEntryPoint аутентификацияEntryPoint; @Бин public SecurityFilterChain filterChain(HttpSecurity httpSecurity) выдает исключение { httpSecurity .cors(Customizer.withDefaults()) .csrf(CsrfConfigurer::отключить) .authorizeHttpRequests(аутентификация -> { аутентификация.requestMatchers(новый AntPathRequestMatcher("/api/user/login"), новый AntPathRequestMatcher("/api/docs/**")).permitAll(); аутентификация.anyRequest().аутентифицированный(); } ) .ExceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(authenticationEntryPoint)) .httpBasic(HttpBasicConfigurer::отключить) .formLogin(FormLoginConfigurer::отключить) .logout(LogoutConfigurer::отключить) .sessionManagement(сессия -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class); вернуть httpSecurity.build(); } @Бин защищенный AuthenticationManager AuthenticationManager () { вернуть новый ProviderManager(Collections.singletonList(dmpAuthenticationProvider)); } @Бин общественный RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter () { Фильтр RequestHeaderAuthenticationFilter = новый RequestHeaderAuthenticationFilter (); filter.setPrincipalRequestHeader("x-auth-dmp-key"); filter.setExceptionIfHeaderMissing(false); filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**")); filter.setAuthenticationManager(authenticationManager()); обратный фильтр; } @Бин CorsConfigurationSource corsConfigurationSource() { Конфигурация CorsConfiguration = новая CorsConfiguration(); Configuration.setAllowedOrigins(List.of("*")); Configuration.setAllowedMethods(List.of("*")); Configuration.setAllowedHeaders(List.of("*")); Configuration.setAllowedOriginPatterns(List.of("*")); Источник UrlBasedCorsConfigurationSource = новый UrlBasedCorsConfigurationSource (); source.registerCorsConfiguration("/**", конфигурация); источник возврата; } } Я пытался добавить что-то подобное в SecurityConfig, но .addFilterAfter HttpSecurity не может быть вызван дважды:
> @Бин защищенный менеджер аутентификации AuthenticationManager2() { вернуть новый ProviderManager(Collections.singletonList(dmpAuthenticationProvider)); } @Бин общественный RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter2 () { Фильтр RequestHeaderAuthenticationFilter = новый RequestHeaderAuthenticationFilter (); filter.setPrincipalRequestHeader(**"x-auth-второй-ключ"**); filter.setExceptionIfHeaderMissing(false); filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**")); filter.setAuthenticationManager(authenticationManager()); обратный фильтр; }
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»