Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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");
}
like image 339
Ashwin Avatar asked Oct 18 '25 03:10

Ashwin


1 Answers

You send username and password parameter as JSON (content type application/json), but you have to send URL-encoded parameters (content type application/x-www-form-urlencoded), see Spring Security Reference:

4 The username must be present as the HTTP parameter named username

5 The password must be present as the HTTP parameter named password

like image 90
dur Avatar answered Oct 20 '25 08:10

dur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!