Мне нужно добавить некоторую пользовательскую логику, например использование службы для регистрации моих неудачных попыток или сброса моих неудачных попыток при успешном входе в систему. Как мне это сделать с помощью httpBasic? Поэтому мне нужен обработчик ошибок и обработчик успеха для httpBasic().
В настоящее время я пытаюсь добавить такой собственный фильтр
Конфигурация безопасности Spring< /p>
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
@Autowired
@Qualifier("customAuthenticationEntryPoint")
AuthenticationEntryPoint authEntryPoint;
@Autowired
@Qualifier("customBasicAuthFilter")
BasicAuthenticationFilter customBasicAuthFilter;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE + 5)
public SecurityFilterChain initSetupSecurityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatcher(AntPathRequestMatcher.antMatcher("/init-setup/**"))
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.requestMatchers(HttpMethod.POST, "/init-setup/otp").permitAll()
.requestMatchers(HttpMethod.GET, "/init-setup/default-client-credentials").authenticated()
.anyRequest().authenticated()
)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .httpBasic(basic -> basic.authenticationEntryPoint(authEntryPoint)) // custom authentication entry point
.addFilterAt(customBasicAuthFilter, BasicAuthenticationFilter.class)
.exceptionHandling(Customizer.withDefaults());
return http.build();
}
}
customBasicAuthFilter
@Component("customAuthenticationFilter")
public class CustomBasicAuthFilter extends BasicAuthenticationFilter {
@Autowired
public CustomBasicAuthFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException {
System.out.println("SUCCESS::");
}
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException {
System.out.println("FAILS::");
}
}
Приложение не запускается и выдает эту ошибку
Parameter 0 of constructor in com.shabodi.laas.config.CustomBasicAuthFilter required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Подробнее здесь: https://stackoverflow.com/questions/788 ... basic-auth
Как обрабатывать успех и неудачу в Springboot для базовой аутентификации? ⇐ JAVA
Программисты JAVA общаются здесь
1722591000
Anonymous
Мне нужно добавить некоторую пользовательскую логику, например использование службы для регистрации моих неудачных попыток или сброса моих неудачных попыток при успешном входе в систему. Как мне это сделать с помощью httpBasic? Поэтому мне нужен обработчик ошибок и обработчик успеха для httpBasic().
В настоящее время я пытаюсь добавить такой собственный фильтр
Конфигурация безопасности Spring< /p>
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {
@Autowired
@Qualifier("customAuthenticationEntryPoint")
AuthenticationEntryPoint authEntryPoint;
@Autowired
@Qualifier("customBasicAuthFilter")
BasicAuthenticationFilter customBasicAuthFilter;
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE + 5)
public SecurityFilterChain initSetupSecurityFilterChain(HttpSecurity http) throws Exception {
http
.securityMatcher(AntPathRequestMatcher.antMatcher("/init-setup/**"))
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.requestMatchers(HttpMethod.POST, "/init-setup/otp").permitAll()
.requestMatchers(HttpMethod.GET, "/init-setup/default-client-credentials").authenticated()
.anyRequest().authenticated()
)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .httpBasic(basic -> basic.authenticationEntryPoint(authEntryPoint)) // custom authentication entry point
.addFilterAt(customBasicAuthFilter, BasicAuthenticationFilter.class)
.exceptionHandling(Customizer.withDefaults());
return http.build();
}
}
customBasicAuthFilter
@Component("customAuthenticationFilter")
public class CustomBasicAuthFilter extends BasicAuthenticationFilter {
@Autowired
public CustomBasicAuthFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException {
System.out.println("SUCCESS::");
}
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException {
System.out.println("FAILS::");
}
}
Приложение не запускается и выдает эту ошибку
Parameter 0 of constructor in com.shabodi.laas.config.CustomBasicAuthFilter required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Подробнее здесь: [url]https://stackoverflow.com/questions/78821644/how-to-handle-success-and-failure-in-springboot-for-basic-auth[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия