SpringSecurity UserDetailsService REST Client

128 Views Asked by At

I'm using SpringBoot 2.4.7 and I'm trying to implement jdbc Authentication. The problem is that I can't reach the backend via http. I have read that with following configuration:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/login")
        .permitAll()
        .and()
        .formLogin()
        ....

I can reach a default login page at my context application address. But I would like to call a POST login endpoint with username and password parameters.

How can I do this?

1

There are 1 best solutions below

1
On

If you are trying to receive the user credentials via a REST Endpoint and manually authenticate the user you can do this way:

@RestController
@RequestMapping("/login")
public class LoginController {
    private final AuthenticationManager authenticationManager;

    // constructor injecting authenticationManager

    @PostMapping
    public void login(@RequestBody UserCredentials credentials) {
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());

        Authentication auth = this.authenticationManager.authenticate(token);

        if (auth != null) {
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(auth);
            SecurityContextHolder.setContext(context);
        }

        throw new SomeException();
    }
}

This way, the Filters will take care of the rest of the authentication steps for you. The Spring Security documentation can be researched for more details.

If you want to use the endpoint generated with the default login page, you can follow the steps from the documentation to make your own request:

  • The form should perform a post to /login
  • The form will need to include a CSRF Token which is automatically included by Thymeleaf.
  • The form should specify the username in a parameter named username
  • The form should specify the password in a parameter named password
  • If the HTTP parameter error is found, it indicates the user failed to provide a valid username / password
  • If the HTTP parameter logout is found, it indicates the user has logged out successfully