Я обнаружил ошибку StackOverflowError в моей конфигурации Spring Security
У меня в приложении есть специальная конфигурация Spring Security, и похоже, что проблема связана с AuthenticationManager . Я уже исключил любые внутренние ошибки Spring и тщательно проверил свой код и конфигурацию.
Код: Выделить всё
java.lang.StackOverflowError: null at java.base/java.lang.reflect.Method.invoke(Method.java:562) ~[na:na] ... Код: Выделить всё
@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig extends SecurityConfigurerAdapter {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.authorizeHttpRequests(customizeRequest -> {
customizeRequest
.anyRequest().permitAll();
})
.httpBasic(Customizer.withDefaults());
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Код: Выделить всё
@RestController
@RequestMapping("log/auth")
public class LogUserController {
private final AuthenticationManager authenticationManager;
private final JwtUtil jwtUtil;
private final UserAppRepository userAppRepository;
@Autowired
public LogUserController(AuthenticationManager authenticationManager, JwtUtil jwtUtil, UserAppRepository userAppRepository) {
this.authenticationManager = authenticationManager;
this.jwtUtil = jwtUtil;
this.userAppRepository = userAppRepository;
}
@PostMapping("/login")
public ResponseEntity login(@RequestBody LoginDto loginDto) {
UsernamePasswordAuthenticationToken login = new UsernamePasswordAuthenticationToken(loginDto.getEmail(), loginDto.getPassword());
Authentication authentication = this.authenticationManager.authenticate(login);
UserDetails userDetails = (UserDetails) userAppRepository.findByEmail(loginDto.getEmail());
String jwt = this.jwtUtil.create(userDetails.getUsername());
return ResponseEntity.ok().header(HttpHeaders.AUTHORIZATION, jwt).build();
}
}
Код: Выделить всё
@Component
public class JwtUtil {
private static String SECRET_KEY = "B9F1498B64CF22D91128C212C8A31";
private static Algorithm ALGORITHM = Algorithm.HMAC256(SECRET_KEY);
public String create(String email) {
return JWT.create()
.withSubject(email)
.withIssuer("pizzeria-pepe-INC")
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(15)))
.sign(ALGORITHM);
}
}
Я столкнулся с проблемой в моей конфигурации Spring Security. У меня есть пользовательская настройка аутентификации с использованием токенов JWT, и когда я делаю запрос POST к конечной точке /login, я сталкиваюсь с ошибкой java.lang.StackOverflowError. Вот что я пробовал:
Проверил свою конфигурацию Spring Security (класс SecurityConfig).
Проверил наличие циклических зависимостей или рекурсивных вызовов в моей логике аутентификации.
Проверил это. с созданием токена JWT в классе JwtUtil проблем нет.
Убедился, что моя реализация UserDetailsService (UserAppService) настроена правильно.
Подробнее здесь: https://stackoverflow.com/questions/772 ... ionmanager
Мобильная версия