Менеджер аутентификации Spring boot 3 и Spring Security 6 застревает на неправильном паролеJAVA

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

Сообщение 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();
} }


Подробнее здесь: https://stackoverflow.com/questions/787 ... on-wrong-p
Ответить

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

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

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

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

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