In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to use Spring Session and Spring security to complete the login transformation of the website, I believe that many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Last time, Xiaohei introduced four implementation methods of distributed consistent Session in his article, of which the most commonly used is the back-end centralized storage solution, so that even if the web application is restarted or expanded, there is no risk of Session loss.
Today we use this way to transform the Session storage mode and store it uniformly in Redis.
Realization scheme
Let's first think about how we can achieve centralized storage in the back-end Session if we don't rely on any framework.
Here we assume that except for some pages, such as the home page, any other pages of our site need to be logged in before they can be accessed.
If we need to implement this requirement, we need to authenticate each request. The purpose of authentication is to determine whether the user is logged in or not and to judge the user's role.
If the user is not logged in, we need to force the request to jump to the login page to log in.
After the user logs in, we need to store the user information obtained by login in Session, so that the later request for authentication only needs to determine whether it exists in the Session.
After knowing the whole process, it is not very difficult to implement the principle.
We can use a principle similar to AOP, after each request comes in, first determine whether the user information exists in the Session, and if not, jump to the login page.
The whole process is as follows:
We can use Servelt Filter to implement the above process, but Spring has already implemented the whole process for us, so we don't have to repeat the wheel.
We can use Spring-Session and Spring-security to implement the process of the above website.
Spring-Session is an implementation that Spring provides to manage user Session. After using Spring-Session, the default WEB container, such as Tomcat, produces Session that will be taken over by Spring-Session.
In addition, Spring-Session also provides several common back-end storage implementations, such as Redis, database and so on.
With Spring-Session, it just helps us solve the Session back-end centralized storage. But we also need login authorization in the above process, and we can use Spring-security to do this.
Spring-security can maintain a unified login authorization method, and it can be used in conjunction with Spring-Session. After the user logs in to the authorization, the user information obtained can be automatically stored in Spring-Session.
All right, cut the crap, let's take a look at the implementation code.
The following is implemented using Spring Boot, and the Spring-Boot version is: 2.3.2.RELEASE
Spring Session
First, we introduce Spring Session dependencies, where we use Redis to store Session information centrally, so we need the following dependencies.
Org.springframework.session spring-session-data-redis
If it is not a Spring Boot project, the main need is to introduce the following dependencies:
Org.springframework.data spring-data-redis 2.3.0.RELEASE org.springframework.session spring-session-core 2.3.0.RELEASE
After introducing dependencies, we first need to add Session-related configurations to application.properties:
# # spring.session.store-type=redis## Session expiration time of Session storage method. The default unit is the prefix spring.session.redis.namespace=test:spring:session## Redis related configuration spring.redis.host=127.0.0.1spring.redis.password=****spring.redis.port=6379 in which sserver.servlet.session.timeout=600## Session is stored to Redis key.
After the configuration is complete, Spring Session will start to manage the Session information. Let's test it:
@ ResponseBody@GetMapping ("/ hello") public String hello () {return "Hello World";}
When we visit the above address and visit Redis, we can see the stored Session information.
Recommend a Redis client "Another Redis DeskTop Manager". This client UI page is very beautiful and easy to operate. Download address:
Https://github.com/qishibo/anotherredisdesktopmanager/releases
By default, Session uses HttpSession serialization by default, which doesn't look intuitive enough. We can modify it to json serialization and store it in redis.
@ Configurationpublic class HttpSessionConfig implements BeanClassLoaderAware {private ClassLoader loader; @ Bean public RedisSerializer springSessionDefaultRedisSerializer () {return new GenericJackson2JsonRedisSerializer (objectMapper ());} / * * Customized {@ link ObjectMapper} to add mix-in for class that doesn't have default * constructors * * @ return the {@ link ObjectMapper} to use * / private ObjectMapper objectMapper () {ObjectMapper mapper = new ObjectMapper () Mapper.registerModules (SecurityJackson2Modules.getModules (this.loader)); return mapper;} @ Override public void setBeanClassLoader (ClassLoader classLoader) {this.loader = classLoader;}}
After modification, the Redis key value is as follows:
Ps: here is the meaning of Redis key value. The next time you analyze the source code, you will do it again.
There is also a @ EnableRedisHttpSession for Spring Session, and we can configure Spring Session-related configuration on this annotation.
@ EnableRedisHttpSession (redisNamespace = "test:session")
It is important to note that if you use this annotation, it will invalidate the configuration related to application.properties Session, that is, Spring Session will directly use the configuration on the annotation.
Here, Blackie recommends that you use the configuration file.
All right, when Spring Session arrives here, we will complete the access.
Spring security
Above we integrated Spring Session to complete Session unified Redis storage. Next, we mainly need to implement the login authentication of the request.
In this step, we use Spring security to achieve a unified login authentication service, the same framework is also Shiro, here we use Spring family bucket.
First of all, we need to rely on the corresponding dependencies:
Org.springframework.boot spring-boot-starter-security
After introducing the above dependency, a random password will be generated after the application is launched, and all requests will be redirected to a Spring security page.
Here we need to implement the landing page of our business, so we need to customize the login verification logic.
In Spring security we only need to implement the UserDetailsService interface and rewrite the loadUserByUsername method logic.
@ Servicepublic class UserServiceImpl implements UserDetailsService {@ Autowired PasswordEncoder passwordEncoder; @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {/ / for simplicity, direct internal verification String uname = "admin"; String passwd = "1234qwer"; / / if it is a formal project, we need to verify the data from the database and then verify it as follows: / / User user = userDAO.query (username) If (! username.equals (uname)) {throw new UsernameNotFoundException (username);} / / encapsulated into the User object return User.builder () .username (username) .passwordEncoder (s-> passwordEncoder.encode (passwd)) .authorities (new SimpleGrantedAuthority ("user")) .build ();}}
The above code is implemented, here is mainly in memory fixed user name and password, in the real environment, we need to modify to query user information from the database.
Then we need to configure UserServiceImpl into Spring security.
@ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@ Autowired UserServiceImpl userService; @ Bean public PasswordEncoder passwordEncoder () {return new BCryptPasswordEncoder () } / * use custom user service to verify login information * * @ param auth * @ throws Exception * / @ Override protected void configure (AuthenticationManagerBuilder auth) throws Exception {/ / user login information verification using custom userService / / also note that password encryption and authentication need to use the same way auth .userDetailsService (userService) .passwordEncoder (passwordEncoder ()) }}
In the above configuration, we use the BCrypt algorithm to encrypt the password. It is important to note that encryption and decryption need to be done in the same way.
Then we need to implement a custom landing page, here do not bother to write their own, directly use the spring-session-data-redis page.
Login Please Login-Invalid username and password. You have been logged out. Username Password remember me: Log in
One thing to note here is that the request address of the form form uses / auth/login, which we need to modify in the following configuration. By default, the login request address needs to be / login.
Then we add the corresponding configuration method to the SecurityConfig class above:
/ * * Custom processing login processing * * @ param http * @ throws Exception * / @ Overrideprotected void configure (HttpSecurity http) throws Exception {http.authorizeRequests ((authorize)-> authorize .requestMatrices (PathRequest.toStaticResources (). AtCommonLocations ()). PermitAll () / / static resources Like css. Js does not need to log in to authentication .anyRequest (). PermitAll () / / other pages need login authentication). FormLogin ((formLogin)-> formLogin / / Custom login page .loginPage ("/ login") / / login page .loginProcessingUrl ("/ auth/login") / / Custom login request address .permitAll () / Of course, the login page does not need authentication. Or wouldn't it be a cub? ) .logout (LogoutConfigurer::permitAll / / logout page) .rememberMe (rememberMe-> rememberMe .rememberMeCookieName ("test-remember") / / Custom remember my cookie name .key ("test") / / Salt value .tokenValiditySeconds (3600 * 12) / / remember me, locally generated cookie contains user information;}
This method may be long, so let's focus on explaining:
You need to specify which pages need authentication in the authorizeRequests method. Here, we specify that there is no need for login authentication for static resources. For other requests, we need login authentication.
Modify the default login page address and the login request address within the formLogin method.
Logout can configure logout-related configurations here.
After rememberMe enables this function, when the internal Session expires, the user can also realize the login-free function according to the Cookie information in the user's browser.
Finally, we need to configure the jump addresses of some pages:
@ Configurationpublic class WebMvcConfig implements WebMvcConfigurer {@ Override public void addViewControllers (ViewControllerRegistry registry) {/ / homepage registry.addViewController ("/") .setViewName ("home"); / / after login, jump to the home page registry.addViewController ("/ login"). SetViewName ("login");}}
So far, we have integrated Spring-Session and Spring-security to complete the login authentication function of the website. From this example, we can see that after the introduction of these two frameworks, we only need to develop according to the Spring specification, and we do not need to implement other complex implementation principles by ourselves, which is really convenient.
After reading the above, have you mastered how to use Spring Session and Spring security to complete the login transformation of the website? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.