Preliminary understanding of Spring Security

 

Preface

Mainly based on the SpringBoot integrated version video of Shang Silicon Valley to learn

The version of SpringBoot in this project is 2.4.1

The version of Spring Security is 5.4.2

 

The code of the controller layer is as follows:

@Controller
public class KungfuController {
	private final String PREFIX = "pages/";
	/**
	 * 欢迎页
	 * @return
	 */
	@GetMapping("/")
	public String index() {
		return "welcome";
	}
	
	/**
	 * 登陆页
	 * @return
	 */
	@GetMapping("/userlogin")
	public String loginPage() {
		return PREFIX+"login";
	}
	
	
	/**
	 * level1页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level1/{path}")
	public String level1(@PathVariable("path")String path) {
		return PREFIX+"level1/"+path;
	}
	
	/**
	 * level2页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level2/{path}")
	public String level2(@PathVariable("path")String path) {
		return PREFIX+"level2/"+path;
	}
	
	/**
	 * level3页面映射
	 * @param path
	 * @return
	 */
	@GetMapping("/level3/{path}")
	public String level3(@PathVariable("path")String path) {
		return PREFIX+"level3/"+path;
	}


}

Based on this, the path of the resource file can be roughly derived

 


 

1. What is Spring Security?

Security framework: lightweight shiro, relatively heavyweight SpringSecurity

Introduce the official original words: Spring Security is a framework that provides authentication, authorization and protection to prevent common attacks. With first-class support for imperative and reactive applications, it is the de facto standard for protecting Spring-based applications

The basic functions of the security framework: authentication and authorization (access control)

Second, use steps

1. Introduce the library:

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

2. Write a configuration class that inherits WebSecurityConfigurerAdapter

The @EnableWebSecurity annotation has declared the @Configuration configuration class, so subclasses do not need to declare this class as a configuration class

Rewrite the protected void configure(HttpSecurity http) method to customize the authorization rules of the request: that is, define the authorization request authorizeRequests() after the client sends a request;

antMatchers("/") sets matching rules, representing all requests

.antMatchers("/level1/**"), which represents all requests under /level1/.

 

@EnableWebSecurity
public class MySecurityConfig 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");
        // 开启自动配置登录功能
        // 1./login来到登录页
        // 2.重定向到/login?error表示登录失败
        // 3.更多详细规定
        http.formLogin();

        // 开启自动配置的注销功能
        // 1.访问/logout 表示用户注销,清空session
        // 2.注销成功会返回 /login?logout 页面
        http.logout().logoutSuccessUrl("/");
    }

    // 定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
    }
}

3. Effect:

If you have not logged in, click any operation to jump to the login page provided by Spring itself.

Guess you like

Origin blog.csdn.net/weixin_41941780/article/details/111829100