username parameter is empty in loadUserByUsername(String username) - spring boot

Viewed 5538

This is my UserDetailService:

public class StockUserDetailService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    private static final Logger logger = Logger.getLogger(StockUserDetailService.class);
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.debug("entering loadByUserName");
        // MongoDatabase database = mongoClient.getDatabase("springsecurity");
        User user = userRepository.findOne(username);
        logger.debug("this is teh user ibzect ="+user);
        if (user == null) {
            logger.info("----------------------------------------------user name is "+username);
            throw new UsernameNotFoundException("NAT FOUND");
        }
        return user;
    }
}

But the username argument always comes as null. I saw tons of other posts on Stackoverflow with the same problem. Some of them say that it is because it expects the username and password as part of HTTP headers rather than a JSON.

But I don't think that is true because Spring Boot's default login page just has a simple form which does a POST request to /login. Which is what I am doing.

I don't understand the problem here.

PS: I have configured by username and password key names properly:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/signup**").permitAll()
            .antMatchers("/login/**").permitAll()
            .antMatchers("/logout/**").permitAll()
            .and()
        .authorizeRequests()
            .antMatchers("/admin/**").hasAuthority("ADMIN")
            .and()
        .formLogin()
            .usernameParameter("username").
            .passwordParameter("password");
}
3 Answers

In my case in the html file I wrote name = "email" I solved it by renaming to "username" because loadUserByUserName expects string with name "username"

<div class = "form-group">
                    <label for ="username">Email </label>:
                    <input type="text" class = "form-control" id ="username" name = "email"
                           placeholder="Enter Email ID" autofocus="autofocus">
                </div>

to:

<div class = "form-group">
                    <label for ="username">Email </label>:
                    <input type="text" class = "form-control" id ="username" name = "username"
                           placeholder="Enter Email ID" autofocus="autofocus">
                </div>
Related