У меня возникла проблема, связанная с менеджером аутентификации. Мой стек включает Spring Security 6.2 и Spring Boot 3.2.
Когда я аутентифицируюсь с помощью существующего пользователя и его пароля, Spring Boot отвечает довольно быстро. Однако, когда я использую неверный пароль, Spring Boot пытается пройти аутентификацию до тех пор, пока не достигнет исключения перехвата неправильных учетных данных, что и ожидалось. Проблема в том, что процесс продолжается через метод, зависает и никогда не возвращает ответ (внутри файла ProviderManager).
AuthController.java
@PostMapping("login")
public ResponseEntity login(@RequestBody LoginRequestDTO loginRequestDTO){
User user = userService.findUserByEmail(loginRequestDTO.getEmail());
if(user == null)
return new ResponseEntity(null, HttpStatus.NOT_FOUND);
UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(
loginRequestDTO.getEmail(), loginRequestDTO.getPassword()
);
Authentication authentication;
try {
authentication = authenticationManager.authenticate(upat); // I added the try-catch block hoping to reach the catch, but it never does, and the method hangs without returning a response
} catch (AuthenticationException e){ // this catch is never reached
return new ResponseEntity(null, HttpStatus.UNAUTHORIZED);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenUtils.createToken(user);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Authorization", "Bearer " + token);
return new ResponseEntity(new LoginResponseDTO(user, token, TokenUtils.createRefreshToken()), responseHeaders, HttpStatus.OK);
}
ProviderManager.java (файл, созданный Springframework)
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { [...Start of the method]
try {
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
catch (AccountStatusException | InternalAuthenticationServiceException ex) {
prepareException(ex, authentication);
// SEC-546: Avoid polling additional providers if auth failure is due to
// invalid account status
throw ex;
}
catch (AuthenticationException ex) {
lastException = ex; // This catch is invoked but the process keeps going
}
}
if (result == null && this.parent != null) { // The process goes inside this and gets stuck
// Allow the parent to try.
try {
parentResult = this.parent.authenticate(authentication);
result = parentResult;
}
catch (ProviderNotFoundException ex) {
// ignore as we will throw below if no other exception occurred prior to
// calling parent and the parent
// may throw ProviderNotFound even though a provider in the child already
// handled the request
}
catch (AuthenticationException ex) {
parentException = ex;
lastException = ex;
}
} [...Rest of the code]
}
SecurityConfig.java
@Configuration @AllArgsConstructor @EnableMethodSecurity public class SecurityConfig {
@Autowired
private final UserDetailsService userDetailsService;
@Autowired
private final JWTAuthorizationFilter jwtAuthorizationFilter;
@Bean
SecurityFilterChain filterChain (HttpSecurity http, AuthenticationManager authManager) throws Exception {
http
.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/api/auth*", "/api/auth/**").permitAll()
.requestMatchers("/api/leader*", "/api/leader/**").hasAnyAuthority("LEADER", "ADMIN")
.requestMatchers("/api/admin*", "/api/admin/**").hasAnyAuthority("ADMIN", "SUBADMIN")
.anyRequest().authenticated()
).csrf(AbstractHttpConfigurer::disable);
// @formatter:on
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder().passwordEncoder(passwordEncoder()::encode)
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
AuthenticationManager authManager(HttpSecurity httpSecurity) throws Exception {
AuthenticationManagerBuilder authManagerBuilder = httpSecurity.getSharedObject(AuthenticationManagerBuilder.class);
authManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
return authManagerBuilder.build();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
} }
Подробнее здесь: https://stackoverflow.com/questions/787 ... on-wrong-p
Менеджер аутентификации Spring boot 3 и Spring Security 6 застревает на неправильном пароле ⇐ JAVA
Программисты JAVA общаются здесь
1720108767
Anonymous
У меня возникла проблема, связанная с менеджером аутентификации. Мой стек включает Spring Security 6.2 и Spring Boot 3.2.
Когда я аутентифицируюсь с помощью существующего пользователя и его пароля, Spring Boot отвечает довольно быстро. Однако, когда я использую неверный пароль, Spring Boot пытается пройти аутентификацию до тех пор, пока не достигнет исключения перехвата неправильных учетных данных, что и ожидалось. Проблема в том, что процесс продолжается через метод, зависает и никогда не возвращает ответ (внутри файла ProviderManager).
AuthController.java
@PostMapping("login")
public ResponseEntity login(@RequestBody LoginRequestDTO loginRequestDTO){
User user = userService.findUserByEmail(loginRequestDTO.getEmail());
if(user == null)
return new ResponseEntity(null, HttpStatus.NOT_FOUND);
UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(
loginRequestDTO.getEmail(), loginRequestDTO.getPassword()
);
Authentication authentication;
try {
authentication = authenticationManager.authenticate(upat); // I added the try-catch block hoping to reach the catch, but it never does, and the method hangs without returning a response
} catch (AuthenticationException e){ // this catch is never reached
return new ResponseEntity(null, HttpStatus.UNAUTHORIZED);
}
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenUtils.createToken(user);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Authorization", "Bearer " + token);
return new ResponseEntity(new LoginResponseDTO(user, token, TokenUtils.createRefreshToken()), responseHeaders, HttpStatus.OK);
}
ProviderManager.java (файл, созданный Springframework)
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { [...Start of the method]
try {
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
catch (AccountStatusException | InternalAuthenticationServiceException ex) {
prepareException(ex, authentication);
// SEC-546: Avoid polling additional providers if auth failure is due to
// invalid account status
throw ex;
}
catch (AuthenticationException ex) {
lastException = ex; // This catch is invoked but the process keeps going
}
}
if (result == null && this.parent != null) { // The process goes inside this and gets stuck
// Allow the parent to try.
try {
parentResult = this.parent.authenticate(authentication);
result = parentResult;
}
catch (ProviderNotFoundException ex) {
// ignore as we will throw below if no other exception occurred prior to
// calling parent and the parent
// may throw ProviderNotFound even though a provider in the child already
// handled the request
}
catch (AuthenticationException ex) {
parentException = ex;
lastException = ex;
}
} [...Rest of the code]
}
SecurityConfig.java
@Configuration @AllArgsConstructor @EnableMethodSecurity public class SecurityConfig {
@Autowired
private final UserDetailsService userDetailsService;
@Autowired
private final JWTAuthorizationFilter jwtAuthorizationFilter;
@Bean
SecurityFilterChain filterChain (HttpSecurity http, AuthenticationManager authManager) throws Exception {
http
.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/api/auth*", "/api/auth/**").permitAll()
.requestMatchers("/api/leader*", "/api/leader/**").hasAnyAuthority("LEADER", "ADMIN")
.requestMatchers("/api/admin*", "/api/admin/**").hasAnyAuthority("ADMIN", "SUBADMIN")
.anyRequest().authenticated()
).csrf(AbstractHttpConfigurer::disable);
// @formatter:on
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder().passwordEncoder(passwordEncoder()::encode)
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
AuthenticationManager authManager(HttpSecurity httpSecurity) throws Exception {
AuthenticationManagerBuilder authManagerBuilder = httpSecurity.getSharedObject(AuthenticationManagerBuilder.class);
authManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
return authManagerBuilder.build();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
} }
Подробнее здесь: [url]https://stackoverflow.com/questions/78708041/spring-boot-3-and-spring-security-6-authentication-manager-gets-stuck-on-wrong-p[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия