In today's Java application development field, Spring Security is a powerful framework for ensuring application security. Its filter chain mechanism is like a precision-operated safety gear set, playing a key role in the security protection of applications. All filters in Spring Security are inherited fromGenericFilterBean
They are connected in a chain in a specific order, performing layer-by-layer security checks and processing of each request entering the application, or performing necessary modifications and verifications on the request, or determining whether it can penetrate into the application based on the characteristics of the request. For example,SecurityContextPersistenceFilter
Always take the lead in loading security contexts from sessions or creating a brand new security context when necessary and storing them inSecurityContextHolder
In the meantime, it will build a solid foundation for subsequent filters and business logic processing. After processing, the request will be passed smoothly to the next filter, likeLogoutFilter
, If the request involves logout operation, it will immediately start the logout process, and then relay in turn, each filter performs its own duties, jointly building an indestructible security barrier.
1. Request filters for initialization stage
(I) SecurityContextPersistenceFilter
Execution order and core tasks
- As the vanguard of the filter chain,
SecurityContextPersistenceFilter
Assessing an extremely important mission. At the beginning of the request, it focuses on initializing the security context. If you request to carryHttpSession
, it will try to extract fromSecurityContext
, and with the help ofSecurityContextHolder
ofsetContext
The method sets it as the security context of the current thread so that subsequent filters and business logic can easily obtain the security information of the current user. likeHttpSession
Does not exist inSecurityContext
, it will decisively create a brand new empty security context to ensure the consistency of the security process. When the request is processed, it will determine whether to set theSecurityContextHolder
The security context information in the restored toHttpSession
, thereby achieving long-term persistence of user security status between multiple requests, like a loyal and reliable guard, always sticking to the position of user security information.
Underlying implementation principle
- Its bottom layer passes
HttpSessionSecurityContextRepository
To implement loading and saving operations of a secure context. existdoFilter
During the execution of the method, you will first carefully try to get from the requestedHttpSession
Get itSecurityContext
, Once successfully obtained, it is quickly set to the security context of the current thread. When the request is processed, it will again determine whether the current security context needs to be saved back based on the configuration.HttpSession
, to ensure that the security context is properly handled at the right time.
(II) LogoutFilter
Logout request processing logic
-
LogoutFilter
occupies an important position in the request processing process related to user logout. When the user initiates a logout operation, such as accessing the default logout URL/logout
Or when a custom logout path is like a trained commander, responding quickly and clearing the user's authentication information, makingSecurityContextHolder
The user authentication information in the instantly fails, and the user status is switched to the unauthenticated state. In addition, it can also perform a series of additional operations related to logout based on the configuration, such as invalidating the session and clearing the related ones.Cookie
etc., completely cut off the connection between users and the current session and ensure system security in all aspects.
Working principle and logout process details
- It will accurately match the URL of the logout request, and once the request matches successfully, it will pass
SecurityContextHolder
ofclearContext
The method decisively clears the security context, as if it cuts off the security link between the user and the system. At the same time, it will callLogoutHandler
The interface implementation class is used to perform specific logout operations. For example,SecurityContextLogoutHandler
Will makeHttpSession
Invalidate, thus clearing all information in the session;CookieClearingLogoutHandler
It can accurately remove authentication-relatedCookie
, effectively prevent users from illegal access with this information.
2. Filters in the certification stage
(I) UsernamePasswordAuthenticationFilter
Form authentication processing process
This is specifically for form-basedUsername - Password
Certified interceptor. When a user fills in the username and password on the login page and submits the form, it is like a keen-eyed scout, quickly intercepting the request, and then accurately extracting the username and password information from the request. It will encapsulate this information intoUsernamePasswordAuthenticationToken
, just like carefully crafting a standard envelope for authentication information, and then solemnly passing this authentication token toAuthenticationManager
Certification. If the authentication is successful, the user can log in to the system smoothly; on the contrary, if the authentication fails, the user will receive corresponding error messages such as username or password errors.
Implementation principle based on AbstractAuthenticationProcessingFilter
Because it inherits fromAbstractAuthenticationProcessingFilter
,existdoFilter
During the implementation of the method, it will first carefully check whether the request is a login request (by matching the login path, the default is/login
). If determined as a login request, it will try to get the username and password from the request. Taking the default form login as an example, it will be like an accurate detector from the requested parameters.username
andpassword
Get the corresponding information in . Then, it will be carefully createdUsernamePasswordAuthenticationToken
Object, this object is like a package full of authentication information, covering key authentication information such as username and password provided by the user. Finally, with the help ofAuthenticationManager
ofauthenticate
Methods: Send this package for certification and wait for the certification results.
Configuration method and sample code
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll(); } }
- exist
Spring Security
The configuration class of (usually inherited fromWebSecurityConfigurerAdapter
) can be passedformLogin
Method to make relevant configuration. For example: - In the above configuration,
formLogin
The method enables the form-based login function.UsernamePasswordAuthenticationFilter
Will automatically be put into work.loginPage("/login")
The path to the login page is clearly specified, and the login page will be presented when the user accesses the path;permitAll
It means that the login page allows all users to access, and even unauthenticated users can successfully access the login page for login operation.
(II) AbstractAuthenticationProcessingFilter
- Abstract authentication processing framework
AbstractAuthenticationProcessingFilter
As an abstract class, it occupies an extremely critical position in Spring Security's certification filter system. It provides a common framework and infrastructure for many specific certification filters, like a solid cornerstone, supporting the implementation of various certification methods. Many specific certification filters, such asUsernamePasswordAuthenticationFilter
etc. are inherited from it, and are personalized expansion and customization based on this.
Core responsibilities and certification process participation methods
- Its core responsibility is to intercept requests related to authentication. It usually checks whether the request complies with a specific authentication path (for example, the default
/login
Path, but this path can be flexibly modified through configuration). When the request matches, it tries to extract the critical information needed for authentication from the request. It will then entrust the heavy responsibility of certification processing toAuthenticationManager
. thisAuthenticationManager
Can be called the core hub of Spring Security certification mechanism, its implementation class (such asProviderManager
) will traverse a series ofAuthenticationProvider
To handle authentication transactions. For example,DaoAuthenticationProvider
Able to obtain user information from databases and other data sources and perform password comparison and peer operations. - If the authentication is successful, it will generate
Authentication
Objects (which contain rich user details, such as permissions, roles, etc.) are properly stored inSecurityContextHolder
middle. thisSecurityContextHolder
It is a global security context container. During the entire request processing process, other components (such as authorization filters) can easily obtain user authentication information from here, thereby performing key operations such as authorization decisions. At the same time, it will also trigger some important events (such as authentication success events). If the corresponding listener is deployed in the application, these events can be captured and additional processing, such as recording logs in detail, updating user login status in a timely manner, etc. - And in the event of authentication failure, it will call
unsuccessfulAuthentication
Method, which by default clears the security context (if present) and can return precise error information to the client according to the configuration. For example, you can configure to return a specific HTTP status code (such as 401 Unauthorized) or a custom error page so that users can understand the reasons for the authentication failure.
(III) DefaultLoginPageGeneratingFilter
Functions and application scenarios for automatically generating login pages
-
DefaultLoginPageGeneratingFilter
Mainly plays a role without a custom login page, it can automatically generate a concise login page. This feature is especially useful during the development and testing phases, and it can quickly provide developers with a available login interface, allowing developers to focus on the core implementation of security features without having to spend a lot of time building login pages in the early stages.
Page generation details and customization options
- The login page it generates has a basic HTML structure, including form fields for entering a username and password, and a prominent submit button. The style of the page is relatively simple and rendered based on HTML. However, it also provides some basic customization options, such as flexibly modifying the form's submission path, username and password field tags, etc. by configuring.
- This filter automatically adjusts the content of the login page according to Spring Security configuration. For example, if multiple authentication methods are configured (such as form-based and HTTP-based basic authentication), it will provide corresponding switching options thoughtfully on the login page, so that users can choose the appropriate authentication method according to their own needs. In addition, it will cleverly set some hidden fields based on the application's security configuration to pass necessary security parameters, such as CSRF (cross-site request forgery) tokens, to enhance the security of the login page.
When to play a role and configuration impact
- When the app starts and no custom login page is found (for example, not passed
formLogin().loginPage("/customLoginPage")
Specify the login page in such a way),DefaultLoginPageGeneratingFilter
It will show off your skills. It intercepts the request (usually a request that accesses a protected resource but the user is not authenticated) and returns an automatically generated login page. If some special parameters or requirements are set in the security configuration, such as custom error message display, remember my function, etc., it will also reflect these configurations as much as possible in the generated login page to provide a more personalized login experience.
(IV) BasicAuthenticationFilter
Detailed explanation of the basic HTTP authentication processing mechanism
- When a client (such as a browser or other HTTP client) uses HTTP basic authentication to send requests,
BasicAuthenticationFilter
The request will be started quickly and intercepted. It is like a professional decoding expert, carefully checking the request headerAuthorization
Field and accurately determine whether the value of the field isBasic
The beginning. If the conditions are met, it will quickly extract and decode the username and password information, and repackage the information intoUsernamePasswordAuthenticationToken
Object, then rely onAuthenticationManager
To complete the authentication process. If the authentication is successful, the request will continue to be processed normally; on the contrary, if the authentication fails, the corresponding error message may be returned according to the configuration, such as the 401 Unauthorized status code, to inform the client of the result of the authentication failure.
Configuration and enable method
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
- Can be passed in
Spring Security
In the configuration classhttpBasic
Method to enable HTTP basic authentication, at this timeBasicAuthenticationFilter
It will take effect automatically. For example: - The above configuration enables HTTP basic authentication. When the client sends a request that meets the HTTP basic authentication requirements,
BasicAuthenticationFilter
The request will be authenticated to ensure that only legally authenticated users can access the corresponding resources.
(V) RememberMeAuthenticationFilter
Analysis of the implementation principle of "Remember Me" function
When the user enables the Remember Me feature and logs in successfully,RememberMeAuthenticationFilter
Then it began to work. It is like a caring memory guardian, who will carefully check in subsequent requests for valid "Remember Me" tokens (usually an encrypted one) in the request.Cookie
). If this token is found, it will useRememberMeServices
(usuallyPersistentTokenBasedRememberMeServices
) to parse the token and extract user identity information from it. It will then create, like other authentication filtersUsernamePasswordAuthenticationToken
The object is and authenticated. If the authentication is successful, the user does not need to enter the user name and password again to access the system and enjoy a convenient login experience; if the authentication fails or the token is invalid, the user may be required to log in again to ensure the security of the system.
Configuration method and parameter description
existSpring Security
Passed in the configuration classrememberMe
Method to configure the "Remember Me" function to enableRememberMeAuthenticationFilter
. For example:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .rememberMe() .rememberMeParameter("remember-me") .tokenValiditySeconds(86400); } }
In the above configuration,rememberMe
The method configures the relevant parameters of "Remember me".rememberMeParameter("remember-me")
The parameter name corresponding to the "Remember Me" option in the front-end form is clearly specified to ensure that the parameters passed by the front-end and back-end in the "Remember Me" function is accurate;tokenValiditySeconds(86400)
The validity period of the token is set to one day (86400 seconds). During this validity period, the user does not need to log in repeatedly. After the validity period exceeds the validity period, the "Remember Me" function may become invalid. The user needs to log in again to achieve a balance between convenience and security.
(VI) X509AuthenticationFilter
Processing process and application scenarios based on certificate authentication
This filter is specially used to handle identity authentication based on X509 certificates. In scenarios with extremely high security requirements, such as sensitive systems within the enterprise or online banking systems of financial institutions, it plays an irreplaceable role. When certificate-based authentication is configured, the interceptor acts like a strict certificate examiner, intercepting requests and carefully checking whether valid X509 certificate information is included in the request. If a certificate exists, it will use its powerful resolution ability to extract relevant identity information from the certificate, such as the user's subject name (Subject Name
)wait. It then follows preconfigured rules such as regular expressions that extract usernames from certificate topics, e.g.x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)")
) to obtain the user's identity and then carefully create an authentication token for authentication. Only users who hold legal and valid certificates can pass the authentication and access relevant resources, thus providing extremely reliable guarantees for system security.
Security advantages compared with traditional authentication methods
In scenarios with extremely high security requirements, authentication based on X509 certificates has significant security advantages compared to traditional username-password authentication methods. Certificates have excellent characteristics such as uniqueness and immutability, which enables them to effectively resist common security threats such as password leakage and brute force cracking. For example, in the online banking system, using X509 certificate authentication can ensure that only legitimate users can log in and conduct transactions with the correct certificate, greatly reducing the risk of account theft and protecting the security of users' funds and the stable operation of the system.
(VII) OAuth2AuthorizationRequestRedirectFilter (suitable for OAuth 2.0 certification)
Processing logic and function of the initial step of OAuth 2.0 authentication
When the application is integratedOAuth 2.0
When certified,OAuth2AuthorizationRequestRedirectFilter
It has become the start key for the entire OAuth 2.0 authentication process. It is responsible for handling requests to redirect users to external authorization servers, like a precise navigator, leading users into the wonderful world of third-party authorization. For example, when a user chooses to log in with a third-party account (such as Google or Facebook account), this interceptor will be based on the configurationOAuth 2.0
Client information (such as client ID, authorization type, redirect URI, etc.), carefully construct the authorization request URL. It then quickly redirects the user to the authorization endpoint of the third-party authorization server, while accurately passing the necessary parameters, such asclient_id
、redirect_uri
、scope
etc., so as to successfully start the third-party authorization process. After the user completes the authorization operation on the third-party authorization server, the subsequent process will be handled by other relevant OAuth 2.0 filter relays.
Importance and Value in Third-Party Login Scenario
In modern web applications, many applications provide convenient functionality to log in with a third-party account, and this interceptor is the core hub for implementing this function. It allows users to quickly log in to the application without registering an account separately in the application, but simply use their existing social accounts, etc., which greatly improves the user experience. At the same time, it also builds a solid bridge for the interaction between applications and third-party authorized servers, ensuring the smooth start of the OAuth 2.0 authentication process, providing users with more diverse and convenient login channels, and promoting interconnection between different applications.
(8) OAuth2LoginAuthenticationFilter (suitable for OAuth 2.0 certification)
Detailed explanation of the process of handling OAuth 2.0 authorization callbacks and authentication completion
During the OAuth 2.0 certification phase,OAuth2LoginAuthenticationFilter
Also plays an extremely important role. When the user completes the authorization on the third-party authorization server, it will be redirected back to the application. At this time, the interceptor is like a smart and capable receiver, responsible for processing the returned authorization code (Authorization Code
) or other related token information. It will quickly obtain authorization code and other information, and then use the configurationOAuth 2.0
Clients (including client ID, client password, etc.) communicate efficiently with third-party authorized servers to obtain user access tokens (Access Token
) and user information. Finally, it will encapsulate this information as an authentication object for authentication, successfully logging the user into the application, completing the entire OAuth 2.0 third-party login process.
Working mechanism with OAuth2AuthorizationRequestRedirectFilter
It is withOAuth2AuthorizationRequestRedirectFilter
Work closely together.OAuth2AuthorizationRequestRedirectFilter
Responsible for redirecting users to a third-party authorization server and starting the authorization process, andOAuth2LoginAuthenticationFilter
After the user authorization is completed, it is responsible for receiving and processing the authorization results. The two complement each other and jointly realize the complete process of OAuth 2.0 third-party login, providing users with a seamless login experience, and also ensuring the security of the application.
(9) OpenIDConnectAuthenticationFilter (applicable to OpenID Connect authentication)
Key processing steps and verification points in the OpenID Connect authentication process
When the application is integratedOpenID Connect
During authentication, the interceptor plays a key role in the authentication process. It will be like a vigilant guard, intercepting fromOpenID Connect
The authentication request of the Identity Provider (IdP) is then used to carefully verify the returned identity token (ID Token
). It will strictly check the legitimacy of the token according to the configured verification algorithm (such as verifying the signature, checking the validity period of the token, etc.). Only a legitimate token can pass verification, and then it will be like an accurate information extractor from a legitimateID Token
Extract user identity-related information, such as user name, user role, etc., encapsulate it as an authentication object and pass it to the authentication manager for authentication. If the authentication is successful, the user can successfully log in to the application; if the authentication fails, the corresponding processing will be performed according to the configuration, such as returning an error message or redirecting to the error page.
Application Value and Advantages in Single Sign-On Solutions
In more and more applicationsOpenID Connect
As a single sign-on solution, this interceptor is implemented withOpenID Connect
A compatible identity authentication system is crucial. It allows users to access multiple applications with unified identity credentials without having to log in separately in each application, greatly improving user experience and work efficiency. At the same time, it also provides strong support for the integration and unified identity management of enterprise-level applications, which facilitates enterprises to centrally manage and control user identities and enhances the security and manageability of the system.
(10) Saml2WebSsoAuthenticationFilter (suitable for SAML 2.0 authentication)
SAML 2.0 Single Sign-On Authentication Request Processing Mechanism and Process
It is used to handle SAML 2.0 (Security Assertion Markup Language) single sign-on (SSO) authentication requests, which are of great significance in enterprise-level applications or cross-organization system integration. In the SAML 2.0 SSO architecture, the interceptor acts like a keen recognizer, identifying and processing SAML authentication requests from the Identity Provider (IdP). It will guide users to interact with IdP and complete the authentication process, just like a professional instructor, ensuring that users move forward smoothly in the complex authentication process. After the user authentication is completed, it receives and parses the SAML response, like a smart parser, extracts user identity information from it, such as the user's name, role, etc., encapsulates it as an authentication object and passes it to the authentication manager for authentication. If the authentication is successful, the user can access relevant resources in the application without barriers; if the authentication fails, the corresponding processing will be carried out according to the configuration.
Advantages and roles in enterprise-level application integration
In scenarios where a unified identity provider is used within the enterprise to provide authentication services to multiple different business systems, this interceptor ensures that users can easily access various systems through the SAML 2.0 SSO mechanism. It realizes seamless user authentication and access across systems, greatly simplifies the user's login process, and improves the integration and user experience of internal systems of the enterprise. At the same time, SAML 2.0 authentication provides high security, can effectively protect the transmission and sharing of user identity information between different systems, and provides reliable guarantees for the security integration of enterprise-level applications.
3. Filters in the authorization stage
(I) FilterSecurityInterceptor
Key roles and responsibilities of final authorization decision making
This interceptor is usually at the last line of defense in the authorization phase and is a key player in making the final authorization decision. It is like a fair judge who strictly reviews and adjudicates requests based on configured access control rules. It will obtain the access control rules corresponding to the requested resource from SecurityMetadataSource, which defines in detail which users or roles can access specific resources. Then, it will obtain the authentication information of the current user from SecurityContextHolder, including user name, role, permissions, etc. Then, it will call the decision method of AccessDecisionManager, pass the access control rules and user authentication information as parameters, and the AccessDecisionManager performs complex authorization decision calculations. If the authorization is successful, the request will be allowed to continue accessing the target resource; if the authorization fails, an AccessDeniedException may be thrown according to the configuration, and the corresponding exception handling mechanism can be configured, such as returning a specific error page or HTTP status code to inform the user of the reason for the access denied.
4. Session management related filters
(I) SessionManagementFilter
Core functions and processes of session management
SessionManagementFilter
Taking the heavy responsibility of conversation management in Spring Security. It is mainly responsible for the full life cycle management of the conversation, like a caring conversation housekeeper who carefully takes care of every link of the conversation. After the user authentication is successful, it will be combined withSecurityContextPersistenceFilter
Finally cooperate.SecurityContextPersistenceFilter
Responsible for storing security contexts (including user authentication information) into HTTP sessions, andSessionManagementFilter
There will be a rigorous inspector to carefully check whether the security context in the session is valid during subsequent request processing. It will verify whether the session has expired, whether it has been tampered with, etc., in order to maintain the integrity and security of the session.
It can also perform concurrent session control configurations, for example, setting up to the number of sessions a user allows to have at the same time. When a user tries to establish a session that exceeds the limit, it will take corresponding measures according to the configuration, such as invalidating the old session or denying new session requests, thereby effectively controlling the number of sessions of the user and ensuring the rational utilization and security of system resources.
To prevent session fixation attacks,SessionManagementFilter
It also plays a key role. Session-fixed attacks are a potential security threat that an attacker attempts to impose a known session ID on the user and then maliciously operates with the session after the user is authenticated.SessionManagementFilter
The session ID can be changed after the user authentication is successful (throughchangeSessionId
Method) to prevent this attack. It creates a new session, migrates information such as security contexts in the old session into the new session, thereby invalidating the session ID acquired by the attacker, as if he has a solid lock on the session to ensure that the session is safe.
Configuration examples and parameter descriptions
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .maximumSessions(2) // Set the maximum number of concurrent sessions to 2 .expiredUrl("/sessionExpired") // When the session expires, redirect to the /sessionExpired page .and() .sessionFixation().newSession(); // Enable session fixed protection, by creating a new session } }
- Here is a simple configuration example to set the maximum number of concurrent sessions to 2 and enable session fixed protection:
- In this configuration,
maximumSessions(2)
It is clearly stipulated that a user can only have two valid sessions at most. If the user tries to log in elsewhere, the previous session will expire.sessionFixation().newSession()
It means that after the authentication is successful, a new session will be created to prevent session fixed attacks and ensure the security and stability of the session.
(II) ConcurrentSessionFilter
Focus on tasks and implementation principles of concurrent session control
ConcurrentSessionFilter
Focusing on the control and management of concurrent sessions, it is like an accurate number of sessions monitors, mainly used to detect whether users exceed the allowed number of concurrent sessions. For example, if a user is configured to have up to three concurrent sessions, it will be like a keen detective, carefully checking whether the current user's session number exceeds this limit.
When it is found that the number of concurrent sessions of a user exceeds the limit, it will take corresponding measures based on the configuration. This usually involves theSessionRegistry
(Session Registry) close interaction,SessionRegistry
Used to track user's session information,ConcurrentSessionFilter
The relevant information will be obtained from it to judge the session status. For example, if configured to invalidate the old session, it will passSessionRegistry
Invalidate old sessions that exceed the limit, and you can choose to redirect the user to a specific page (such as prompting the user's session has expired or informing the user that he has logged in elsewhere), thereby effectively controlling the number of concurrent sessions of the user and ensuring the security and stability of the system.
Differences and collaboration relationships with SessionManagementFilter
Functional focus differences:
SessionManagementFilter
Focus on the full life cycle management of the session, including the storage of the security context in the session, the creation and verification of the session, concurrent session control, and prevention of session fixed attacks. It is more like a comprehensive conversation manager, from the birth to the end of the conversation, ensuring the security and effectiveness of the conversation in all aspects.
ConcurrentSessionFilter
The focus is on the control of the number of concurrent sessions. The main task is to monitor the user's concurrent session situation and take corresponding measures when it is found that the limit is exceeded. It is more like a dedicated concurrent session supervisor focusing on the management of the specific aspect of the number of sessions.
Collaborative and coordination mechanism:
In practical applications,SessionManagementFilter
andConcurrentSessionFilter
Cooperate with each other to build a powerful conversation management mechanism.SessionManagementFilter
Under the overall framework of session management, session creation, verification and basic concurrent session control operations, andConcurrentSessionFilter
On the basis of this, further strengthen the precise monitoring and management of the number of concurrent sessions. For example,SessionManagementFilter
After the maximum number of concurrent sessions is configured,ConcurrentSessionFilter
It will check in real time and perform operations such as invalidating the old session when necessary. The two complement each other and provide a solid guarantee for the security of the application's session.
5. Filters in exception handling stage
(I) ExceptionTranslationFilter
Core responsibilities and processes for exception handling
When an exception occurs during the execution of the security filter chain,ExceptionTranslationFilter
It will play a key role, it is like a keen exception catcher and processing coordinator. It is mainly responsible for handling two types of exceptions:AuthenticationException
(Authorization exception) andAccessDeniedException
(Authorization rejection exception).
ForAuthenticationException
, If the user has not been authenticated, it will redirect the user to the login page according to the configuration, giving the user the opportunity to re-authenticate the operation to obtain legal access. For example, if a user attempts to access a protected resource without logging in, such an exception will be triggered.ExceptionTranslationFilter
It will be directed to the login page, and usually it will carry some relevant information during redirection, such as the original requested URL, so that the user can be automatically redirected back to the resource page he was trying to access after login is successful.
ForAccessDeniedException
, If the user has been authenticated but does not have sufficient permission to access a specific resource, it will decide what to do based on the configuration. It may be to display an error page with access denied, and to clearly inform the user that he does not have enough permissions to access the resource; it may also be to execute some custom logic, such as logging, notifying the administrator, etc., in order to further follow up and process the security policy.
Configuration examples and flexibility
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .accessDeniedPage("/accessDenied") // Set the error page path when access is denied .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")); // Set the login entry page when unauthenticated } }
- exist
Spring Security
In the configuration class, you canExceptionTranslationFilter
Configure the behavior of . For example: - In the above configuration,
accessDeniedPage("/accessDenied")
It clearly specifies when it happensAccessDeniedException
When the user is redirected to/accessDenied
Page, This page can show users detailed access denied information.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
Then set the trigger of unauthenticated userAuthenticationException
The login page is/login
, ensure that users can successfully enter the authentication process to obtain legal permissions. This configuration method allows developers to flexibly customize exception handling logic according to the specific needs of the application, improving the security and user experience of the application.
VI. Other supplementary filters or related mechanisms
(I) CsrfFilter
CSRF Attack Protection Principle
CsrfFilter is mainly used to prevent cross-site request forgery (CSRF) attacks. In today's web environment, CSRF attacks are a common security threat, and attackers try to induce users to perform malicious actions while logged in. CsrfFilter generates a random CSRF token when the user accesses the page and stores it in the user's session or page (usually a hidden field). When a user submits a form or performs other critical actions, the filter checks whether the request contains the correct CSRF token. If the token is missing or incorrect, the filter will determine that the request may be a CSRF attack, thus denying the request, effectively protecting the user's account security and the integrity of the application data.
Interaction with forms and AJAX requests
- For form submission, CsrfFilter embeds the CSRF token into the hidden fields of the form when the page is rendered. When a user submits a form, the filter checks whether the token in this field is consistent with the token stored on the server side. For example, in a form where a user submits an order, CsrfFilter ensures that only requests carrying a legitimate CSRF token can submit the order successfully, preventing attackers from forgery of order submission requests.
- For AJAX requests, a CSRF token is usually passed in the request header. CsrfFilter checks the token information in the request header to ensure the security of AJAX operations. For example, in an application that uses AJAX for data updates, only AJAX requests containing the correct CSRF token can be accepted by the server and perform data update operations to prevent malicious AJAX calls from tampering with data.
Configuration and customization options
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .csrfTokenRepository(()) .ignoringAntMatchers("/public-api/**"); } }
In Spring Security configuration, CsrfFilter can be customized. For example, the token generation policy, storage location, etc. can be configured. Here is a simple configuration example:
In the above configuration,csrfTokenRepository(())
Storing CSRF tokens in cookies and allowing JavaScript access (in certain specific scenarios, if you need to obtain tokens in front-end JavaScript, it should be used with caution, as it may increase security risks).ignoringAntMatchers("/public-api/**")
Indicates for/public-api/
The URL path at the beginning ignores CSRF protection, which is more common in some public API endpoint settings without CSRF protection. Developers can flexibly configure it according to the actual security needs of the application.
(II) CorsFilter (cross-domain resource sharing filter)
Cross-domain request processing mechanism
In modern web application development, cross-domain resource sharing (CORS) has become an important issue because the front-end and back-end may be deployed under different domain names or ports. CorsFilter is a filter used to handle cross-domain requests. It will add corresponding cross-domain information to the response header according to the configured cross-domain rules, such asAccess-Control-Allow-Origin
(Allowed source),Access-Control-Allow-Methods
(Allowed methods),Access-Control-Allow-Headers
(Allowed header information) etc. When the browser receives these header information, it will determine whether front-end JavaScript code is allowed to access the cross-domain resource based on its rules.
Configuration examples and support for multiple cross-domain scenarios
Here is a simple CorsFilter configuration example:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { ().configurationSource(request -> { CorsConfiguration corsConfiguration = new CorsConfiguration(); ("http://localhost:3000"); ("GET"); ("POST"); ("*"); return corsConfiguration; }); } }
In the above configuration, for thehttp://localhost:3000
source, allow it to be usedGET
andPOST
The method makes cross-domain requests and allows all header information. This is in the development environment, the current application runs inhttp://localhost:3000
And it is very useful when you need to interact with the backend across domains. In actual applications, multiple allowed sources, methods and header information can be configured according to different business needs to meet complex cross-domain scenarios, such as interacting with front-end applications of multiple different domain names, or fine-grained control of specific types of requests (such as only requests with specific header information are allowed to cross-domain) to ensure the security and compliance of applications during cross-domain access.
(III) ChannelProcessingFilter
Channel security-based processing logic
ChannelProcessingFilter focuses on applying corresponding security policies based on requested channels such as HTTP or HTTPS. In today's network security-focused environment, ensuring the security of data transmission across different channels is crucial. It checks the type of protocol requested, and if the configuration requires that some resources must be accessed through a secure channel (such as HTTPS) and the request is sent over a non-secure channel (such as HTTP), the filter can redirect the user to the corresponding secure channel URL. For example, for pages or resources involving important operations such as user login and sensitive data transmission, when configuration requires HTTPS, if the user accesses through HTTP, ChannelProcessingFilter will automatically redirect the request to the corresponding HTTPS link to ensure the confidentiality and integrity of the data during transmission.
Configuration method and flexible application
In Spring Security configuration, you can set the channel processing rules like this:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .antMatchers("/secure/**").requiresSecure() .antMatchers("/insecure/**").requiresInsecure(); } }
In the above configuration, for/secure/**
The resources under the path clearly require that they must be accessed through secure channel (HTTPS); and for/insecure/**
Resources under the path are allowed to be accessed through unsafe channels (HTTP). This flexible configuration method allows developers to accurately define channel access rules according to the security needs of different resources in the application, ensuring security while also taking into account the normal access of some non-sensitive resources with special requirements for performance or other aspects, and optimizing the overall performance and user experience of the application.
(IV) SecurityContextHolderAwareRequestFilter
Functional implementations integrated with Servlet API
This filter builds a bridge between Spring Security and the Servlet API, which makes it easier to obtain Spring Security's security context information in Servlet-related components. In traditional Servlet programming, directly accessing security contexts may be more cumbersome, while SecurityContextHolderAwareRequestFilter wraps the original Servlet request and provides some convenient ways to obtain user authentication information, role information, etc. For example, in a custom Servlet, the user name of the currently logged-in user can be directly obtained through the request object wrapped by the filter, without delving into the underlying API of Spring Security for complex operations, simplifying the processing logic of security information during development.
Improve the convenience of application development
It greatly improves the convenience of integrating Spring Security in Servlet-based applications. Developers can incorporate security-related logic more naturally based on existing Servlet code. For example, in a servlet that processes user requests, different response content can be dynamically generated based on the role information of the current user, providing personalized services to users of different permission levels. This helps improve the readability and maintainability of the code, so that the security functions of the application can be better integrated with the business logic, reduce the development and maintenance costs caused by the separation of security mechanisms and business code, and promote efficient development and stable operation of the application.
(V) AnonymousAuthenticationFilter
Anonymous user authentication processing process
AnonymousAuthenticationFilter intervenes when a request enters the system without authenticating the real user. It creates an anonymous authentication object (AnonymousAuthenticationToken) for unauthenticated requests and stores it in SecurityContextHolder. In this way, in subsequent filter chain processing and application business logic, even unauthenticated users can be processed in a unified way, avoiding null pointer exceptions or other logical confusion caused by user unauthorized. For example, in some applications, access to certain public resources is also allowed for unlogged users, but access logs may be required. At this time, the anonymous authentication object provided by AnonymousAuthenticationFilter can be used to identify visitors' identity information in the logging module, ensuring that the system can fully track all access behaviors, whether from authenticated users or anonymous users.
Configuration and application scenarios
In Spring Security configuration, you can set the relevant attributes of anonymous authentication, such as the role name, permissions, etc. of anonymous users. Here is a simple example:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .authorities("ROLE_ANONYMOUS") .key("anonymousKey"); } }
In the above configuration, the role is set for anonymous users to be "ROLE_ANONYMOUS" and a key "anonymousKey" is specified for some encryption or identification operations when creating anonymous authentication objects. This configuration is very useful in some scenarios where anonymous users and authenticated users' permissions are required. For example, in a forum system, users who are not logged in (anonymous users) can only view posts but cannot post comments. By configuring the role and permissions of anonymous users, they can accurately control their operating range in the system and ensure the security and normal operation of the system's functions.
(VI) RequestCacheAwareFilter
Request cache and recovery mechanism
RequestCacheAwareFilter is mainly responsible for handling request cache-related operations. In some cases, if the user is redirected to the login page without authentication, the login needs to be returned to the previously requested page, and the original request needs to be cached and restored. This filter checks whether a cached request exists during the request processing, and if so, restores it and continues to process it. For example, if a user accesses a protected product details page without logging in, he is redirected to the login page. After logging in successfully, RequestCacheAwareFilter can retrieve the previous product details page request from the cache and re-execute the request, so that the user can successfully see the page he wanted to access before, providing a good user experience.
Working in conjunction with other filters
It works in conjunction with filters like ExceptionTranslationFilter. When ExceptionTranslationFilter handles authentication exceptions and redirects the user to the login page, the original request information is cached, while RequestCacheAwareFilter restores the cached request at the appropriate subsequent time. This collaborative mechanism ensures that the user's request process can be reasonably interrupted and restored during the processing of the entire security filter chain, so that the application can still maintain good interactivity and coherence when processing complex logic such as user authentication and authorization, and avoid users losing request information or confusion due to the intervention of the security mechanism.
7. Shared data mechanism (SecurityContextHolder)
Core role and data storage
SecurityContextHolder is a critical container in Spring Security for storing security context information. It plays a core role in data sharing during the entire request processing process, and stores information related to the current user authentication and authorization, such as Authentication objects (including detailed information such as user identity, role, permissions, etc.). In a typical request processing process, starting from the successful user authentication, the relevant authentication information is stored in the SecurityContextHolder, and in subsequent authorization filters (such as FilterSecurityInterceptor) and the application's business logic, the user's security information can be easily obtained from this container, thereby deciding whether to allow the request to continue execution or perform corresponding business operations. For example, in an enterprise resource management system, when a user logs in successfully, his user information, department roles and other information are stored in SecurityContextHolder. When the user accesses different business modules (such as inventory management, sales order processing, etc.), the codes of each module can directly obtain user role information from SecurityContextHolder to determine whether the user has corresponding operation permissions. For example, only users with the inventory administrator role can modify the inventory quantity.
Thread binding and multi-threaded environment considerations
SecurityContextHolder uses thread binding to store security context information. This means that in a multi-threaded environment, each thread has its own independent SecurityContext. In a web application, each user request is usually processed by an independent thread, which ensures that the security information of different users will not be confused with each other. For example, in a highly concurrent e-commerce system, multiple users initiate requests at the same time, and the corresponding thread of each request will only access and operate the SecurityContext bound to its own thread during processing, ensuring the security and independence of user data. However, in some special multithreading scenarios, such as using a thread pool to handle asynchronous tasks, if you need to access the information in the SecurityContextHolder in the asynchronous task, you need to pay special attention to the transmission and processing of the thread context to avoid the loss of security information or incorrect acquisition due to thread switching. Developers can adopt some strategies, such as saving the SecurityContext of the current thread before submitting an asynchronous task, and setting it to the corresponding thread when the asynchronous task is executed, ensuring that the security information can be used correctly during the asynchronous task processing and ensuring the safe and stable operation of the entire application in a multi-threaded environment.
This is the end of this article about the use of built-in filters in SpringSecurity. For more related SpringSecurity built-in filter content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!