简体   繁体   中英

Spring Security authenticate logic

Endpoint security in Spring security is achieved with a list of filters. I need one clarification.

Suppose a filter has successfully authenticated a request and set the the authentication object in the security context. That filter also has called filterchain.dofilter(). Assume that the authentication.isAuthenticated() returns true - the filter has already set it.

If the authentication object in the security context returns true if isAuthenticated() is called, will the subsequent filters ignore authentication process (means they won't call authenticationmanager.authenticate())? Or will they still call authenticationmanager.authenticate () even if the isAuthenticated() returns true on the authentication object retrieved from the security context? Assume that the request path matches with the filter configuration (that means subsequent filters also will see the request as the request servlet path matches their configuration)

Thanks in advance.

I'll try to answer as detailed as possible.

First of all, it's true that Spring Security uses a filter chain, but usually, the authentication starts from one of the filters in the chain. If you authenticate your users in multiple ways, then you need to implement multiple authentication providers (AuthenticationProvider). Take a look at figure 1. The authentication starts from the filter level and the responsibility is taken by a manager, named AuthenticationManager. The manager finds an AuthenticationProvider that fits. Figure 1

In certain cases, you might want to implement multiple authentication filters. Say you have a custom multi-factor authentication (MFA) solution. But it is you who decides which filters are skipped. By default, the request follows each filter in the chain.

You can design a filter to be skipped if you implement the OncePerRequestFilter and override the shouldNotFilter() method to tell the filter when it doesn't apply.

In conclusion:

  • to implement authentication in multiple ways you use authentication providers
  • the subsequent filters will see the request unless you explicitly make them skip it
  • I do also recommend you the first part of the book I wrote on Spring Security - Spring Security in Action. You'll find a more detailed description on how authentication, authorization and the filter chain works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM