In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how Spring Security deals with Session sharing". In daily operation, I believe many people have doubts about how Spring Security deals with Session sharing. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how Spring Security handles Session sharing". Next, please follow the editor to study!
1. Cluster session scheme
In the traditional single-service architecture, generally speaking, if there is only one server, there is no Session sharing problem, but in distributed / cluster projects, Session sharing is a problem that must be faced. First, take a look at a simple architecture diagram:
In such an architecture, there will be some problems that do not exist in a single service, such as the client initiates a request. After the request arrives on Nginx, it is forwarded to Tomcat A by Nginx, and then a data is saved in session on Tomcat A. next time, the request is forwarded to Tomcat B, and then go to Session to get the data and find that there is no previous data.
1.1 session Sharin
At present, the mainstream solution to this kind of problem is to save the data that needs to be shared among various services in a public place (the mainstream solution is Redis):
When all Tomcat needs to write data to Session, it writes to Redis, and when all Tomcat needs to read data, it reads from Redis. In this way, different services can use the same Session data.
Such a solution can be manually implemented by developers, that is, manually storing data in Redis and manually reading data from Redis, which is equivalent to using some Redis client tools to achieve such a function. There is no doubt that manual implementation is still a lot of work.
A simplified solution is to use Spring Session to achieve this function. Spring Session uses the proxy filter in Spring to intercept all Session operations, automatically synchronize data to Redis, or automatically read data from Redis.
For developers, all Session synchronization operations are transparent, developers use Spring Session, once configured, the specific usage is the same as using a normal Session.
1.2 session copy
Session copy is to copy session data directly between each Tomcat without using redis, but this method is a bit inefficient. Any session in Tomcat A, B, C needs to be copied to other Tomcat. If there are a large number of servers in the cluster, this method is not only inefficient, but also has serious latency.
Therefore, this kind of scheme can be used as an understanding.
1.3 sticky conversation
The so-called sticky session is that requests sent from the same IP are routed to the same Tomcat through Nginx, so that there is no need for session sharing and synchronization. This is an approach, but in some extreme cases, it can lead to load imbalance (because in most cases, many people use the same public network IP).
Therefore, Session sharing has become the mainstream solution to this problem.
2.Session sharing
2.1 create a project
First, create a Spring Boot project, introducing Web, Spring Session, Spring Security, and Redis:
After the creation is successful, the pom.xml file is as follows:
Org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web org.springframework.session spring-session-data-redis
2.2 configuration
Spring.redis.password=123 spring.redis.port=6379 spring.redis.host=127.0.0.1 spring.security.user.name=javaboy spring.security.user.password=123 server.port=8080
Configure the basic information of Redis; Spring Security to simplify, I will configure the user name and password directly in the application.properties, and finally configure the project port number.
2.3 use
After the configuration is completed, you can use Spring Session. In fact, you can use ordinary HttpSession, other Session synchronization to Redis and other operations, and the framework has automatically completed it for you:
@ RestController public class HelloController {@ Value ("${server.port}") Integer port; @ GetMapping ("/ set") public String set (HttpSession session) {session.setAttribute ("user", "javaboy"); return String.valueOf (port);} @ GetMapping ("/ get") public String get (HttpSession session) {return session.getAttribute ("user") + ":" + port;}}
Considering that Spring Boot will be started in a cluster later, in order to get the service provided by which Spring Boot provides each request, you need to return the port number of the current service on each request, so here I inject server.port.
Next, the project is packaged:
After packaging, start two instances of the project:
Java-jar session-4-0.0.1-SNAPSHOT.jar-server.port=8080 java-jar session-4-0.0.1-SNAPSHOT.jar-server.port=8081
Then first visit localhost:8080/set to save a variable in the Session of the 8080 service. The first visit will automatically jump to the login page and enter the user name and password to log in. After successful access, the data has been automatically synchronized to the Redis:
Then, by calling the localhost:8081/get interface, you can get the data in the session of the 8080 service:
At this point, the configuration of session sharing is complete, and we have seen the effect of session sharing.
2.4 Security configuration
Session sharing has been implemented, but we have found a new problem. How can we get rid of logged-in users if we separate the project in front and back of Spring Boot + Vue? The session concurrency management that we configured in this article has failed.
That is, if I add the following configuration:
Protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests (). AnyRequest ()... sessionManagement () .maximumSessions (1) .maxSessionsPreventsLogin (true);}
Now this configuration doesn't work, and users can still log in on multiple browsers at the same time.
What's going on?
In this article, we mentioned that the maintenance of the session registry is maintained by default by SessionRegistryImpl, while the maintenance of SessionRegistryImpl is based on memory. Now we have enabled Spring Session+Redis for Session sharing, but SessionRegistryImpl is still maintained based on memory, so we need to modify the implementation logic of SessionRegistryImpl.
The modification method is also very simple. In fact, SpringSession provides us with the corresponding implementation class SpringSessionBackedSessionRegistry, which is configured as follows:
@ Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Autowired FindByIndexNameSessionRepository sessionRepository; @ Override protected void configure (HttpSecurity http) throws Exception {http.authorizeRequests () .sessionManagement () .sessionManagement () .maximumSessions (1) .maxSessionsPreventsLogin (true) .sessionReg istry (sessionRegistry ()) } @ Bean SpringSessionBackedSessionRegistry sessionRegistry () {return new SpringSessionBackedSessionRegistry (sessionRepository);}}
All we need to do here is to provide an instance of SpringSessionBackedSessionRegistry and configure it into sessionManagement. In the future, the maintenance of session concurrent data will be done by SpringSessionBackedSessionRegistry, not SessionRegistryImpl, so our configuration on session concurrency will take effect, and in a cluster environment, users can only log in on one device.
To make our case look more perfect, let's introduce Nginx to automatically switch service instances.
3. Introduction of Nginx
Quite simply, go to the conf directory of Nginx's installation directory (default is / usr/local/nginx/conf), and edit the nginx.conf file:
In this configuration:
Upstream means to configure an upstream server
Javaboy.org represents the name of the server cluster, which can be named at will
Individual services are configured in upstream.
Weight represents the weight of the service, which means what percentage of requests will be forwarded from the Nginx to the service
The proxy_pass in location indicates the address of the request to be forwarded, / indicates that all requests are intercepted and forwarded to the service cluster that has just been configured
Proxy_redirect indicates that when a redirect request occurs, nginx automatically corrects the response header data (by default, Tomcat returns the redirection. In this case, the redirected address is the address of Tomcat, and we need to change it to the address of Nginx).
After the configuration is completed, upload the local Spring Boot packaged jar to Linux, and then start two Spring Boot instances on Linux:
Nohup java-jar session-4-0.0.1-SNAPSHOT.jar-server.port=8080 & nohup java-jar session-4-0.0.1-SNAPSHOT.jar-- server.port=8081 &
Among them
Nohup indicates that Spring Boot should not stop running when the terminal shuts down.
& means to let Spring Boot start in the background
After the configuration is complete, restart Nginx:
/ usr/local/nginx/sbin/nginx-s reload
After the Nginx starts successfully, we first manually clear the data on the Redis, and then access 192.168.66.128/set to save the data to the session. The request will first go to the Nginx, and then be forwarded to a Spring Boot instance by Nginx:
As above, the Spring Boot with port 8081 processes the / set request, and then accesses the / get request:
As you can see, the / get request is processed by the service with port 8080.
At this point, the study on "how Spring Security handles Session sharing" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.