This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

springSecurity

introduce

Spring Security is a powerful and highly customizable authentication and access control framework. It’s actually a standard for protecting Spring-based applications.

Spring Security is a framework that focuses on providing authentication and authorization for Java applications. As with all Spring projects, the real power of Spring security is that it can be easily extended to meet custom requirements

function

Spring Security is based on the Spring framework, providing a complete set of Web application Security solutions. Generally speaking, Web application security includes two parts, Authentication and 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 authenticates the user name and password. User authorization refers to verifying that a user has the right to perform an operation. In a system, different users have different permissions. For example, some users can only read a file, while others can modify it. Generally speaking, the system assigns different roles to different users, and each role corresponds to a set of rights.

The Spring Security framework has good support for both of the application scenarios mentioned above. In terms of user authentication, the Spring Security framework supports the mainstream authentication methods, including HTTP basic authentication, HTTP form authentication, HTTP digest authentication, OpenID, AND LDAP. On the user authorization side, Spring Security provides role-based Access Control and Access Control Lists (ACLs) for fine-grained Control over domain objects in an application.

The premise

1. Create the project, select Web and SQL API, MySQL Driver

2. Import themyLeaf template

3. Create a static resource

4. Write the controller

@org.springframework.stereotype.Controller public class Controller { @RequestMapping({"/","/index"}) public String index(){ return "index"; } @RequestMapping("/toLogin") public String tologin(){ return "views/login"; } // second @requestMapping ("/level1/{id}") public String leavel1(@pathVariable ("id") int id){return "views/level1/"+id; } @RequestMapping("/level2/{id}") public String leavel2(@PathVariable("id") int id){ return "views/level2/"+id; } @RequestMapping("/level3/{id}") public String leavel3(@PathVariable("id") int id){ return "views/level3/"+id; }}Copy the code

Start the configuration

Introduce the spring-boot-starter- Security module

The configuration class

  • WebSecurityConfigurerAdapter custom Security strategy
  • AuthenticationManagerBuilder custom authentication strategy
  • EnableWebSercurity Enables the WebSecurity mode

1. The package

<dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-security</artifactId>
       </dependency>
Copy the code

2. Create a configuration class, inheritance WebSecurityConfigurerAdapter, add @ EnableWebSercurity annotation

Set the permissions required to access the content

@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void Configure (HttpSecurity HTTP) throws Exception {// Http.authorizerequests ().antmatchers ("/").permitall ().antmatchers ("/level1/**").hasrole ("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); // No permission to display denied access is ugly, so jump to the login page http.formlogin (); }}Copy the code

3. Run4. Add the statement http.formlogin ();Go to the login page without permissionYou can replace the login page created by Security with one you wrote yourself

// Customize the loginPage http.formlogin ().loginPage("/toLogin");Copy the code

5. User authentication permission

Create several users and grant permissions

PasswordEncoder @override protected void if the springBoot version is 2.1.x or later Configure (AuthenticationManagerBuilder auth) throws the Exception {/ / the data can be read from the database, can also be read from the memory, Fast auth. InMemoryAuthentication (.) passwordEncoder (new BCryptPasswordEncoder ()) .withUser("YY").password(newBCryptPasswordEncoder().encode("123456")).roles("vip1") .and().withUser("YZY").password(newBCryptPasswordEncoder().encode("123456")).roles("vip2"); }}Copy the code

6. Log in to YY (permission VIP1), select vip2’s web page, and forbid

7. Log out

The cancellation of the source code

After formLogin, add http.logout();

8. You want the user with the specified permission not to see the content of other permissions

Home page

<! --> <div SEC :authorize="! IsAuthenticated () "> < a class =" item "th: href =" @ {/ toLogin} "> < I class =" address card icon "> < / I > login < / a > < / div > <! <div SEC :authorize="isAuthenticated()"> <a class="item"> <div SEC :authentication="name"> <div sec:authentication="authorities"></div> </a> <a class="item" th:href="@{/logout}"> <i class="address card </div> </div> <! --> <div SEC :authorize="hasRole('vip2')" class="column">< div class=" UI Raised segment"> <div class=" UI Raised segment"> <div class="ui"> <div class="content"> <h5 class="content">Level 2</h5> <hr> <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i>Level-2-1</a></div> <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i>Level-2-2</a></div> <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i>Level-2-3</a></div> </div> </div> </div> </div> <div sec:authorize="hasRole('vip3')" class="column"></div>Copy the code