eprats
eprats

Reputation: 345

Why the authentication should be implemented in a filter and not in a controller?

Following a good tutorial about how to implement JWT authentication in a Spring Boot application (https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/), I have seen that the /login is handled by a filter and not by a controller. And this is not a Bruno's caprice, Spring is offering itself a filter (UsernamePasswordAuthenticationFilter and so).

Why use a filter? Is it because it is placed before the authorization filter and this way we can intercept a new login attempt without being affected by the authentication filter?

Thanks! Enric

Upvotes: 5

Views: 637

Answers (1)

git-flo
git-flo

Reputation: 1064

The filter chain is one of spring-security core-concepts. The intro of the spring-security documentation explains the benefits as following:

Spring Security's web infrastructure is based entirely on standard servlet filters. [...]

Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required.

Generally speaking: You use a framework like spring for handling standard application-flows like in your case authentication and login. The concept of spring-security for dealing with this is the filter chain. Due to the fact that using a framework comes alongside some payoffs (e.g. overhead), it is highly recommended to use the possibilities the framework offers you.

In your case the /login is handled by the UsernamePassworAuthenticationFilter. This filter brings along some standard logic for login-proceeding and handles authentication and is therefore not handled by a controller.

The filter (UsernamePassworAuthenticationFilter) calls the configured AuthenticationManager to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the AuthenticationSuccessHandler and AuthenticationFailureHandler strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely

Upvotes: 3

Related Questions