UsernamePasswordAuthenticationFilter vs own endpoint

Viewed 123

Let's say I want to handle an api endpoint /login, which gets a username&password body and returns a JWT token in a header.

What's the difference between using UsernamePasswordAuthenticationFilter with

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    try {
        LoginDto loginDto = new ObjectMapper().readValue(request.getInputStream(), LoginDto.class);
        return getAuthenticationManager().authenticate(
            new UsernamePasswordAuthenticationToken(
                loginDto.getUsername(),
                loginDto.getPassword(),
                Collections.emptyList()
            )
        );
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

over providing my own @PostMapping("/login"), where I call a UserService myself? What's the reason/advantage for calling a filter on a single endpoint?

1 Answers

The main advantage of UsernamePasswordAuthenticationFilter is a better integration with Spring than your custom login request. Using it the framework provides you nices ways to:

  • Manage events like: after a successful login, an unsuccesful login and after a successful logout.

  • The result of that filter is an Spring Authentication object so, you will be able to use it in "the rest of login request" if you need.

Some examples about how to use it (in both ones you will see how your UserService should be configured):

UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter + JWT

However, manage your own login endpoint is a widely used option too. If you really don't need/use the above advantages, it is suitable to create your own endpoint to manage that request.

Related