authenticationManager threw StackOverFlow

My end point http://localhost:8080/auth/login doesn't work, it always throws StackOverFlow. java.lang.StackOverflowError: null at org.springframework.aop.support.AopUtils.isEqualsMethod(AopUtils.java:166) ~[spring-aop-6.2.2.jar:6.2.2] at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:175) ~[spring-aop-6.2.2.jar:6.2.2] at jdk.proxy2/jdk.proxy2.$Proxy145.authenticate(Unknown Source) ~[na:na] at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
No description
No description
No description
30 Replies
JavaBot
JavaBot3d ago
This post has been reserved for your question.
Hey @Tomás! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
ayylmao123xdd
ayylmao123xdd3d ago
the image with the code isnt visible at all just paste it here
dan1st | Daniel
@RestController @RequestMapping(value = "/auth")
public class AuthController {

private AuthenticationManager authenticationManager;
private UserRepository userRepository;
private TokenService tokenService;

public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TokenService tokenService) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.tokenService = tokenService;
}

@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthDTO data) {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.email(), data.password());
var auth = authenticationManager.authenticate(usernamePassword);

var token = tokenService.generateToken((User) auth.getPrincipal());

return ResponseEntity.ok(new LoginResponseDTO(token));
}

@PostMapping("/register")
public ResponseEntity register(@RequestBody @Valid RegisterDTO data) {
if (this.userRepository.findByEmail(data.email()) != null) return ResponseEntity.badRequest().build();

String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
User newUser = new User(null, data.name(), data.email(), data.phone(), encryptedPassword, data.role());

this.userRepository.save(newUser);

return ResponseEntity.ok().build();
}
}
public class AuthController {

private AuthenticationManager authenticationManager;
private UserRepository userRepository;
private TokenService tokenService;

public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TokenService tokenService) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.tokenService = tokenService;
}

@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthDTO data) {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.email(), data.password());
var auth = authenticationManager.authenticate(usernamePassword);

var token = tokenService.generateToken((User) auth.getPrincipal());

return ResponseEntity.ok(new LoginResponseDTO(token));
}

@PostMapping("/register")
public ResponseEntity register(@RequestBody @Valid RegisterDTO data) {
if (this.userRepository.findByEmail(data.email()) != null) return ResponseEntity.badRequest().build();

String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
User newUser = new User(null, data.name(), data.email(), data.phone(), encryptedPassword, data.role());

this.userRepository.save(newUser);

return ResponseEntity.ok().build();
}
}
This message has been formatted automatically. You can disable this using /preferences.
Tomás
TomásOP3d ago
the imports package ecomerce.api.controllers; import ecomerce.api.domain.DTOs.AuthDTO; import ecomerce.api.domain.DTOs.LoginResponseDTO; import ecomerce.api.domain.DTOs.RegisterDTO; import ecomerce.api.domain.User; import ecomerce.api.infra.security.TokenService; import ecomerce.api.repositories.UserRepository; import jakarta.validation.Valid; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
ayylmao123xdd
ayylmao123xdd3d ago
show auth manager
dan1st | Daniel
@Configuration @EnableWebSecurity
public class SecurityConfigurations {

private SecurityFilter securityFilter;

public SecurityConfigurations(SecurityFilter securityFilter) {
this.securityFilter = securityFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .authorizeHttpRequests(authorize -> authorize
// .requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
// .requestMatchers(HttpMethod.POST, "/auth/register").permitAll()
// .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
// .anyRequest().authenticated()
// )
// .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
public class SecurityConfigurations {

private SecurityFilter securityFilter;

public SecurityConfigurations(SecurityFilter securityFilter) {
this.securityFilter = securityFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .authorizeHttpRequests(authorize -> authorize
// .requestMatchers(HttpMethod.POST, "/auth/login").permitAll()
// .requestMatchers(HttpMethod.POST, "/auth/register").permitAll()
// .requestMatchers(HttpMethod.GET, "/swagger-ui/**").permitAll()
// .anyRequest().authenticated()
// )
// .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
This message has been formatted automatically. You can disable this using /preferences.
Tomás
TomásOP3d ago
It's from import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
ayylmao123xdd
ayylmao123xdd3d ago
try to add static to the authentication manager bean and see if it works
Tomás
TomásOP3d ago
ok same error
ayylmao123xdd
ayylmao123xdd3d ago
show how u changed the code
Tomás
TomásOP3d ago
private static AuthenticationManager authenticationManager;
ayylmao123xdd
ayylmao123xdd3d ago
no not here
@Bean
public static AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public static AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
here
Tomás
TomásOP3d ago
yeah, same
ayylmao123xdd
ayylmao123xdd3d ago
did you delete the static from the private field
Tomás
TomásOP3d ago
yes
Tomás
TomásOP3d ago
GitHub
GitHub - tomas-barros1/e-commerce-api-spring: Esta é uma API que si...
Esta é uma API que simula uma espécie de e-commerce desenvolvida com Spring Boot, MySQL e Docker. A API permite gerenciar produtos, categorias, usuários, pedidos e pagamentos . - tomas-barros1/e-co...
ayylmao123xdd
ayylmao123xdd3d ago
interesting
Tomás
TomásOP3d ago
the register end point works
ayylmao123xdd
ayylmao123xdd3d ago
do you have more than one authentication provider or authentication configuration
Tomás
TomásOP3d ago
no
ayylmao123xdd
ayylmao123xdd3d ago
@Bean
AuthenticationManager myAuthenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider::authenticate;
}
@Bean
AuthenticationManager myAuthenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder);
return provider::authenticate;
}
try this
Tomás
TomásOP3d ago
** APPLICATION FAILED TO START ** Description: Field userDetailsService in ecomerce.api.infra.security.SecurityConfigurations required a bean of type 'org.springframework.security.core.userdetails.UserDetailsService' that could not be found. Action: Consider defining a bean of type 'org.springframework.security.core.userdetails.UserDetailsService' in your configuration.
ayylmao123xdd
ayylmao123xdd3d ago
you need to define user details service bean for testing purposes do this
Tomás
TomásOP3d ago
User details service class is provided by spring
ayylmao123xdd
ayylmao123xdd3d ago
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
try this
Tomás
TomásOP3d ago
i dont have any erros anymore when i try to login
Tomás
TomásOP3d ago
No description
ayylmao123xdd
ayylmao123xdd3d ago
😱 crazy right you have to define your own user details service though cuz the code i pasted is for testing
JavaBot
JavaBot3d ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?