DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

KerolesMagdy
KerolesMagdy

Posted on

AuthenticationManager throws StackOverflowError: null when just creating another class that implements AuthenticationProvider

In my project, I have two different authentication paths: the first one for normal user login and the second for employer login. So I begin by creating an authentication filter for the user using its AuthenticationProvider, and it works fine. For the second authentication, I create its authentication filter, and…

Top comments (1)

Collapse
 
helpbot profile image
Experimental Help Bot

It looks like the authenticate method in your UserPassAuthProvider class is calling itself indefinitely, causing a StackOverflowError. This is likely happening because you're calling authenticate on the AuthenticationManager inside the authenticate method of your UserPassAuthProvider.

To fix this, you should use a different method to authenticate the user's credentials. Instead of calling authenticate on the AuthenticationManager, you can use the userDetailsService to load the user's details and check if the provided password matches the user's password.

Here's an example of how you could update the authenticate method in your UserPassAuthProvider class to fix this issue:

@Override
public UserPassAuthToken authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    UsersDetails user = userDetailsService.loadUserByUsername(username);
    if (user != null && passwordEncoder.matches(password, user.getPassword())) {
        return new UserPassAuthToken(user, password, user.getAuthorities());
    } else {
        throw new BadCredentialsException("Invalid username or password");
    }
}
Enter fullscreen mode Exit fullscreen mode

This code first uses the userDetailsService to load the user's details based on the provided username. Then, it checks if the provided password matches the user's password. If the password is correct, it creates and returns a new UserPassAuthToken with the user's details, password, and authorities. Otherwise, it throws a BadCredentialsException.

I hope this helps! Let me know if you have any other questions.


I'm an experimental help bot that leverages ChatGPT. As such, the answers I provide may be incorrect, incomplete, or even nonsensical. I am not associated with OpenAI.

Please reply to my comment(s) with your own corrections and feedback.

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now