Import dependence

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

Routing control

@Controller
public class RouterController {
    @GetMapping("/index")
    public String index(a){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String login(a){
        return "login";
    }
    @RequestMapping("/level1/{id}")
    public String Level1(@PathVariable("id") int id){
        return "level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String Level2(@PathVariable("id") int id){
        return "level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String Level3(@PathVariable("id") int id){
        return "level3/"+id; }}Copy the code

User authentication

Through inheritance WebSecurityConfigurerAdapter @ EnableWebSecurity and use to open the security

package com.demo.Config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        / / authorization
        // Request rules, the home page is accessible to all, the function page is partially accessible
        http.authorizeRequests().antMatchers("/").permitAll()
        // Vip1 can access all under /level1/**
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        // If the user does not have permission, the user will automatically jump to the login page
        http.formLogin();
        
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        Lin has permissions on vip1 and vip2
        auth.inMemoryAuthentication().
                .withUser("lin").password("123456").roles("vip1"."vip2")
                .and()
                .withUser("admin").password("123456").roles("vip1"."vip2"."vip3")
                .and()
                .withUser("guest").password("123456").roles("vip1"); }}Copy the code

It says there is no Passwordencoder mapped so you need to code the authorized object

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"."vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"."vip2"."vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
Copy the code

The cancellation

Add http.logout().logOutSuccessURL (“/”) to configure(HttpSecurity HTTP);

Http.logout () Enables logout, and logoutSuccessUrl(“/”) sets the address to jump to after the logout is successful

@Override
    protected void configure(HttpSecurity http) throws Exception {
        / / authorization
        // Request rules, the home page is accessible to all, the function page is partially accessible
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        http.formLogin();
        http.logout().logoutSuccessUrl("/");
        //http.httpBasic();
    }
Copy the code

To allow users with different permissions to see different parts of the page

Import dependence

<! -- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-springsecurity5</artifactId>
			<version>3.0.4. RELEASE</version>
		</dependency>
Copy the code

Setting the namespace

<html lang="en" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"  >
Copy the code

Modify the part that displays login and logout so that the login button can be seen by the logged in user and the login button can be seen by the unlogged user

The IsAuthenticated attribute is a Boolean value indicating whether the current user IsAuthenticated (logged in).

The property value is a Boolean true if the current user is authenticated, false otherwise.

<! --// Not logged in -->
<div sec:authorize=! "" isAuthenticated()">
<a href="/toLogin">The login</a>
</div>
<! - / / login -- -- >
<div sec:authorize="isAuthenticated()">
<a href="/logout">The cancellation</a>
    <a class="item">User name:<span sec:authentication="name"></span> <! Get user name -->Role:<span sec:authentication="authorities"></span>
    </a>
</div>
Copy the code

In the same way, modify the original display page part ‘

Note: hasRole is appended with the prefix ROLE_ when making permission judgments. `

<! DOCTYPE html> <html lang="en" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"  >
<head>
    <meta charset="UTF-8"> <title>Title</title> </head> <body> <! --// Not logged in -->
<div sec:authorize=! "" isAuthenticated()">
<a href="/toLogin"> Login </a> </div> <! --/ / login -- -- >
<div sec:authorize="isAuthenticated()">
<a href="/logout"> logout </a> <aclass="item"> User name :<span SEC :authentication="name"></span> Role :<span SEC :authentication="authorities"></span>
    </a>
</div>
<div sec:authorize="hasRole('vip1')">
    <a href="level1/1">level1-1</a><br>
    <a href="level1/2">level1-2</a><br>
    <a href="level1/3">level1-3</a><br>
</div>

<div sec:authorize="hasRole('vip2')">
<a href="level2/1">level2-1</a><br>
<a href="level2/2">level2-2</a><br>
    <a href="level2/3">level2-3</a><br>
</div>
<div sec:authorize="hasRole('vip3')">
<a href="level3/1">level3-1</a><br>
<a href="level3/2">level3-2</a><br>
<a href="level3/3">level3-3</a><br>
</div>
</body>
</html>
Copy the code

Remember me

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
     
        // Enable the remember me function, use cookies to store,
        RememberMeParameter Specifies the name of the parameter used to activate the Remember Me function. Remember -me is the default
        http.rememberMe().rememberMeParameter("remember-me"); }}Copy the code

The front page

<form action="/a" method="post">User name:<input type="text" name="name">
    <br>Password:<input type="password" name="pwd">
    <br><input type="checkbox" name="remember-me">remember me
    <input type="submit">
</form>
Copy the code

Custom home page

Note: Error 403 was reported during the test because Spring Security enabled CSRF protection by default

However, our form lacks token and is forbidden to access

(Quoted from the network www.cnblogs.com/it-deepinmi… Blog.csdn.net/csdnluolq/a…).

You can add the corresponding token or http.csrf().disable() according to the spring file; Close the CSRF


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // Enable remember me function, cookie, set the parameter name used to activate remember me function, default remember-me
        http.rememberMe().rememberMeParameter("remember-me");
        //loginPage sets the url of the loginPage. If the user does not login, any resources will be forwarded to this path
        http.formLogin().loginPage("/toLogin").
                // enter the name of the username input box in the login form. If you do not change the name, the default is username
                usernameParameter("name").
                // The name of the password input box in the form. If you do not change the password, the default password is password
                passwordParameter("pwd").
                // The address of the action in the login form, which is the path to the authentication request
                loginProcessingUrl("/a").
                // Default path to switch to after successful login authentication
                defaultSuccessUrl("/"); }}Copy the code

Essay: CSRF

HttpSecurity http

http.csrf().disable(); Close the CSRF

Cross-site request forgery Cross-site Request Forgery, also known as one-click attack or session riding, usually abbreviated as CSRF or XSRF, Is a method of hijacking a user to perform unintended actions on a currently logged Web application. In contrast to cross-site scripting (XSS), which exploits the user’s trust in a given site, CSRF exploits the site’s trust in the user’s Web browser.