In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "what are the Spring Security resource release strategies". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the Spring Security resource release strategies.
In Spring Security, how to release additional resources?
1. Two ways of thinking
In Spring Security, there is a resource, and if you want users to access it without logging in, generally speaking, you have two configuration strategies:
The first is to configure release in the configure (WebSecurity web) method, like this:
@ Override
Public void configure (WebSecurity web) throws Exception {
Web.ignoring () .antMatchers ("/ css/**", "/ js/**", "/ index.html", / img/** "," / fonts/** "," / favicon.ico "," / verifyCode ")
}
The second way is to configure it in the configure (HttpSecurity http) method:
Http.authorizeRequests ()
.antMatch ("/ hello") .permitAll ()
.anyRequest () .authenticated ()
The biggest difference between the two ways is that the first way is not to take the Spring Security filter chain, while the second way is to take the Spring Security filter chain, in which the request is released.
When we use Spring Security, some resources can be released in the first way and can be configured in the first way without verification, such as static resources on the front-end page.
If some resources are released, the second method must be used, such as the login interface. As we all know, the login interface must also be exposed and can be accessed without login, but we cannot expose the login interface in the first way. Login requests must go through the Spring Security filter chain, because there are other things to do in the process.
Next, I'll take the login interface as an example to analyze the difference between walking the Spring Security filter chain with my friends.
two。 Login request analysis
First of all, as you know, when we use Spring Security, after the user logs in successfully, there are two ways to get the user login information:
SecurityContextHolder.getContext () .getAuthentication ()
In the method of Controller, add the Authentication parameter
In both ways, the information of the currently logged-in user can be obtained.
The data obtained by these two methods come from the data in SecurityContextHolder,SecurityContextHolder, which is essentially saved in ThreadLocal. ThreadLocal is characterized by the existence of the data in it, which thread stores and which thread can access.
This brings a problem, when the user login is successful, the user data is stored in SecurityContextHolder (thread1), when the next request comes (thread2), want to get the user login information from SecurityContextHolder, but find that can not get it! Why? Because they are not the same Thread.
But in fact, under normal circumstances, after we successfully log in with Spring Security, we will be able to get the login user information every time. What is the matter?
This is what we are going to introduce into Spring Security
SecurityContextPersistenceFilter.
As we all know, whether it is Spring Security or Shiro, a series of functions are actually accomplished by filters. In Spring Security, I talked to you earlier.
UsernamePasswordAuthenticationFilter filter, before this filter, there is another filter is
SecurityContextPersistenceFilter, the request arrives
UsernamePasswordAuthenticationFilter always passes by before.
SecurityContextPersistenceFilter .
Let's take a look at its source code (part):
Public class SecurityContextPersistenceFilter extends GenericFilterBean {
Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain)
Throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req
HttpServletResponse response = (HttpServletResponse) res
HttpRequestResponseHolder holder = new HttpRequestResponseHolder (request
Response)
SecurityContext contextBeforeChainExecution = repo.loadContext (holder)
Try {
SecurityContextHolder.setContext (contextBeforeChainExecution)
Chain.doFilter (holder.getRequest (), holder.getResponse ())
}
Finally {
SecurityContext contextAfterChainExecution = SecurityContextHolder
.getContext ()
SecurityContextHolder.clearContext ()
Repo.saveContext (contextAfterChainExecution, holder.getRequest ())
Holder.getResponse ()
}
}
}
The original method is very long, and I have listed a few key parts here:
SecurityContextPersistenceFilter inherits from GenericFilterBean, and GenericFilterBean is the implementation of Filter, so as a filter, the most important method in SecurityContextPersistenceFilter is doFilter.
In the doFilter method, it will first read a SecurityContext from repo, where the repo is actually HttpSessionSecurityContextRepository, and the operation of reading SecurityContext will go into the readSecurityContextFromSession method. Here we see the core method of reading Object contextFromSession = httpSession.getAttribute (springSecurityContextKey); where the value of the springSecurityContextKey object is SPRING_SECURITY_CONTEXT, and the read object will eventually be converted into a SecurityContext object.
SecurityContext is an interface that has a unique implementation class SecurityContextImpl, which is actually the value where user information is stored in session.
After getting the SecurityContext, set the SecurityContext to the ThreadLocal through the SecurityContextHolder.setContext method, so that in the current request, the subsequent operations of the Spring Security can obtain the user information directly from the SecurityContextHolder.
Next, continue the request through chain.doFilter (this time it goes into the UsernamePasswordAuthenticationFilter filter).
After the filter chain is completed and the data response is sent to the front end, there is one more closing step in finally, which is critical. Here, the SecurityContext is obtained from the SecurityContextHolder. After getting it, the SecurityContextHolder is emptied, and then the repo.saveContext method is called to store the acquired SecurityContext in the session.
At this point, the whole process is very clear.
When each request arrives at the server, first find the SecurityContext from the session, and then set it to the SecurityContextHolder for subsequent use. When the request leaves, the SecurityContextHolder will be emptied and the SecurityContext will be put back into the session to facilitate the next request to obtain.
When the login request comes, there is no login user data, but when the login request leaves, the user login data will be stored in session, and when the next request comes, it can be directly taken out and used.
Looking at the above analysis, we can draw at least two conclusions:
If we use the first method mentioned above when exposing the login interface, without Spring Security and filter chain, the login user information will not be stored in session after the login is successful, resulting in subsequent requests unable to obtain login user information (subsequent requests are also unauthenticated requests in the eyes of the system)
If your login request is normal and goes through the Spring Security filter chain, but the subsequent A request does not go through the filter chain (released in the first way mentioned above), then the login user information cannot be obtained through SecurityContextHolder in the A request, because it did not go through the SecurityContextPersistenceFilter filter chain at first.
3. Summary
In short, when the front-end static resources are released, you can simply not follow the Spring Security filter chain, as shown below:
@ Override
Public void configure (WebSecurity web) throws Exception {
Web.ignoring () .antMatchers ("/ css/**", "/ js/**", "/ index.html", / img/** "," / fonts/** "," / favicon.ico ")
}
If you want to release additional backend APIs, you need to carefully consider the scenario. However, generally speaking, the above method is not recommended. The following method is recommended. The reasons have been mentioned earlier:
Http.authorizeRequests ()
.antMatch ("/ hello") .permitAll ()
AnyRequest (). Authenticated () so far, I believe you have a deeper understanding of "what are the Spring Security resource release strategies". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.