chappalprasad
chappalprasad

Reputation: 855

spring security StackOverflow Error

I am implementing security in spring boot application and receiving StackOverflow exception. i have a User pojo and repository to save user in DB which is working fine.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;
    ....
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .userDetailsService(userDetailsService); }

and

public class User {

    private String password;

    public User(User user) {
        this.password = user.password;
        ...
    }

    public String getPassword() {
        return password;
    }

expecting User's getPassword() to get called below but not happening -

public class MyUserDetails extends User implements UserDetails{
    ........
    @Override
    public String getPassword() {
        return getPassword();
}

Implementation of UserDetailsService -

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    User user = userRepository.findByEmail(email);
    if (user == null)
         throw new UsernameNotFoundException("no " + email);
    return new MyUserDetails(user);
}

I have inserted one user/password in DB by calling userRepository.save(user). When i try to pass invalid user/password , it is returning invalid user message correctly. But when i try with user/password stored in DB i get following exception -

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Filter execution threw an exception] with root cause

java.lang.StackOverflowError: null
    at com.xyz.MyUserDetails.getPassword(MyUserDetails.java:27) ~[classes/:na]

Upvotes: 1

Views: 2736

Answers (1)

Morfic
Morfic

Reputation: 15528

Taking a look at MyUserDetails.getPassword() method, you can see that it will call itself... infinitely...

public class MyUserDetails extends User implements UserDetails{
    ........
    @Override
    public String getPassword() {
        return getPassword(); // <= infinite recursion here
}

Was there perhaps a variable with a similar name that you wanted to return, or maybe call a different method (from the super class.. or not..)?

Upvotes: 1

Related Questions