In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to use Spring Security". In daily operation, I believe many people have doubts about how to use Spring Security. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Spring Security"! Next, please follow the editor to study!
Brief introduction to SpringSecurity Security
Security has always been a very important aspect in Web development. Although security belongs to the non-functional requirements of the application, it should be considered in the early stages of application development. If you consider security at a later stage of application development, you may be caught in a dilemma:
1. On the one hand, there are serious security loopholes in the application, which can not meet the requirements of users, and may cause users' privacy data to be stolen by attackers.
2. On the other hand, the basic architecture of the application has been determined, in order to fix security vulnerabilities, it may need to make significant adjustments to the architecture of the system, so it needs more development time to affect the release process of the application. Therefore, security-related factors should be taken into account from the first day of application development, and in the whole application development process.
There is a more famous one on the market: Shiro,Spring Security!
What needs to be explained here is that each framework is created to solve a problem, so what problem is the emergence of the Spring Security framework to solve?
First of all, let's take a look at its official website introduction: Spring Security official website address
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements
Spring Security is a powerful and highly customizable authentication and access control framework. It is actually the standard for protecting spring-based applications.
Spring Security is a framework that focuses on providing authentication and authorization for Java applications. Like all Spring projects, the real power of Spring security is that it can be easily extended to meet custom requirements
It can be seen from the introduction of the official website that this is an authority framework. How do we control permissions without using the framework to do the project before? Permissions are generally subdivided into
Functional authority
Access permission
Menu permissions
Using Filter to write all kinds of permissions will make the code very tedious and redundant.
How to solve the tedious and redundant problem of writing permission code before, some mainstream frameworks emerge as the times require, and Spring Scecurity is one of them.
Spring is a very popular and successful Java application development framework. Based on the Spring framework, Spring Security provides a complete solution for the security of Web applications. Generally speaking, the security of Web application includes two parts: user authentication (Authentication) and user authorization (Authorization). User authentication refers to verifying whether a user is a legitimate principal in the system, that is, whether the user can access the system. User authentication generally requires the user to provide a user name and password. The system completes the authentication process by verifying the user name and password. User authorization refers to verifying that a user has permission to perform an operation. In a system, different users have different permissions. For example, for a file, some users can only read it, while others can modify it. In general, the system assigns different roles to different users, and each role corresponds to a series of permissions.
For the two application scenarios mentioned above, the Spring Security framework has good support.
1. In terms of user authentication, Spring Security framework supports mainstream authentication methods, including HTTP basic authentication, HTTP form verification, HTTP summary authentication, OpenID and LDAP, etc.
2. In the aspect of user authorization, Spring Security provides role-based access control and access control list (Access Control List,ACL), which can control the domain objects in the application with fine granularity.
Construction of experimental environment for practical testing
1. Create an initial springboot project web module and thymeleaf module.
2. Import static resources
Welcome.html | views | level1 1.html 2.html 3.html | level2 1.html 2.html 3.html | level3 1.html 2.html 3.html Login.html
3. Controller Jump!
Package com.sowhat.controller; import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping; @ Controllerpublic class RouterController {@ RequestMapping ({"/", / index "}) public String index () {return" index ";} @ RequestMapping (" / toLogin ") public String toLogin () {return" views/login " } @ RequestMapping ("/ level1/ {id}") public String level1 (@ PathVariable ("id") int id) {return "views/level1/" + id;} @ RequestMapping ("/ level2/ {id}") public String level2 (@ PathVariable ("id") int id) {return "views/level2/" + id;} @ RequestMapping ("/ level3/ {id}") public String level3 (@ PathVariable ("id") int id) {return "views/level3/" + id }}
4. Test whether the experimental environment is OK!
Get to know SpringSecurity
Spring Security is the security framework for Spring project, and it is also the default technology selection of Spring Boot underlying security module. It can achieve powerful Web security control. For security control, we only need to introduce spring-boot-starter-security module and make a small amount of configuration to achieve powerful security management!
Remember several classes:
WebSecurityConfigurerAdapter: custom Security policy
AuthenticationManagerBuilder: custom authentication policy
@ EnableWebSecurity: enable WebSecurity mode
The two main goals of Spring Security are authentication and authorization (access control).
Authentication (Authentication)
Authentication is about verifying your credentials, such as user name / user ID and password, to verify your identity.
Authentication is usually done through a user name and password, sometimes in combination with authentication factors.
Authorization (Authorization)
Authorization occurs after the system successfully verifies your identity, and eventually gives you full access to resources such as information, files, databases, funds, locations, and almost any content.
This concept is universal, not just in Spring Security.
Authentication and authorization
At present, our test environment is accessible to anyone, and we use Spring Security to add authentication and authorization functions.
1. Introduce Spring Security module
Org.springframework.boot spring-boot-starter-security
2. Write Spring Security configuration class
Reference official website: https://spring.io/projects/spring-security
Check the version in our own project and find the corresponding help document: documentation
3. Write basic configuration classes
Package com.sowhat.config; import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @ EnableWebSecurity / / enable WebSecurity mode public class SecurityConfig extends WebSecurityConfigurerAdapter {@ Override protected void configure (HttpSecurity http) throws Exception {}}
4. Customize the configure method content of the authorization rule of the custom request.
@ Overrideprotected void configure (HttpSecurity http) throws Exception {/ / customize the authorization rules of the request / / the owner of the home page can access, and the rest need role permission to access http.authorizeRequests (). AntMatchers ("/"). PermitAll () .antMatrices ("/ level1/**"). HasRole ("vip1") .antMatrices ("/ level2/**"). HasRole ("vip2") .antMatrices ("/ level3/**"). HasRole ("vip3");}
5, test: found that except for the home page can not get into! Because we currently do not have a login role, because the request requires the login role to have the corresponding permissions!
6. Add the following configuration in the configure () method. If you do not have permission to access several URLs, then jump to the landing page directly! FormLogin
/ / enable auto-configured login function / login request to login page / login?error redirect here indicates login failure http.formLogin ()
7, test: found that when there is no permission, will jump to the login page (SpringSecurity comes with the login page)!
8. Check the comment information on the login page just now
We can define authentication rules and override the configure (AuthenticationManagerBuilder auth) method
/ / define the authentication rule @ Overrideprotected void configure (AuthenticationManagerBuilder auth) throws Exception {/ / define it in memory, or you can get it in jdbc. Auth.inMemoryAuthentication () .withUser ("sowhat"). Password ("123456"). Roles ("vip2", "vip3") .and (). WithUser ("root"). Password ("123456"). Roles ("vip1", "vip2", "vip3") .and () .withUser ("guest"). Password ("123456"). Roles ("vip1", "vip2");}
9, testing, we can use these accounts to log in for testing! If you find out, you will make a mistake!
There is no PasswordEncoder mapped for the id "null"
10. The reason is that we have to encrypt the password passed from the front end in some way, otherwise we will not be able to log in and modify the code
/ / define the authentication rule @ Overrideprotected void configure (AuthenticationManagerBuilder auth) throws Exception {/ / define it in memory, or you can get it in jdbc. / / Spring security 5.0added a variety of encryption methods, but also changed the format of the password. / / in order for our project to log in normally, we need to modify the code in configure. We need to encrypt the password passed from the front end in some way / / spring security officially recommends using bcrypt encryption. Auth.inMemoryAuthentication () .passwordEncoder (new BCryptPasswordEncoder ()) .withUser ("sowhat") .password (new BCryptPasswordEncoder (). Encode ("123456")) .roles ("vip2", "vip3") .and () .withUser ("root") .password (new BCryptPasswordEncoder () .encode ("123456")) .roles ("vip1", "vip2") "vip3") .and () .withUser ("guest") .password (new BCryptPasswordEncoder () .encode ("123456")) .roles ("vip1", "vip2") }
11, test, found that the login is successful, and each role can only access the rules under its own authentication! Done.
Access control and logout
1. Enable the auto-configured logout function
/ / customize the authorization rule of the request @ Overrideprotected void configure (HttpSecurity http) throws Exception {/ /.... / / enable auto-configured logout function / logout logout request http.logout ();}
2. At the front end, we add a logout button (the login page that comes with the system), in the index.html navigation bar
Write off
3, we can go to test, after logging in successfully, click logout, and find that the logout will jump to the login page!
4. However, we want him to skip to the home page after he has successfully logged off. What should we do?
/ / .logoutSuccessUrl ("/"); logout successfully comes to the home page http.logout () .logoutSuccessUrl ("/")
5. Test. After logging out, you find that you jump to the custom home page OK.
6. Now we have another requirement: when the user does not log in, only the login button is displayed on the navigation bar. After the user logs in, the navigation bar can display the login user information and the logout button! There is, for example, sowhat this user, it only has vip2,vip3 functions, then login only displays these two functions, but the function menu of vip1 does not show! This is the real website situation! What should be done?
We need to combine some of the functions in thymeleaf
Sec:authorize= "isAuthenticated ()": whether to authenticate login or not! To display different pages
Maven dependencies:
Org.thymeleaf.extras thymeleaf-extras-springsecurity5 3.0.4.RELEASE
7. Modify our front-end page
Import Namespace
Xmlns:sec= "http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
Modify the navigation bar to add certification judgment
Login user name: role: log out
8. Restart the test. We can log in and try it. After the login is successful, it shows the page we want.
9. If you log out of 404, it is because it prevents csrf cross-site request forgery by default. Because of security problems, we can change the request to post form submission, or turn off the csrf function in spring security. Let's try: add http.csrf () .disable () to the configuration.
Http.csrf () .disable (); / / disable csrf function: cross-site request forgery. By default, you can only submit logout request http.logout () .logoutSuccessUrl ("/") through post.
10. Let's continue to complete the certification of the following role function blocks!
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.