SpringBoot-Security

一、Spring Security

1. Basic concepts

Two security frameworks: shiro, Spring Security

Spring Security is a security framework for the Spring project and the default technology selection for the underlying security module of Spring Boot. He can achieve powerful web security control. For security control, we only need to introduce the spring-boot-starter-security module and perform a small amount of configuration to achieve strong security management.

  • WebSecurityConfigurerAdapter: Custom Security Strategy
  • AuthenticationManagerBuilder: custom authentication strategy
  • @EnableWebSecurity: Turn on WebSecurity mode

The two main areas where applications deal with security issues are "authentication" and "authorization" (access control):

  • "Authentication" (Authentication): mainly refers to the process of verifying the subject through username/password.
  • "Authorization": Refers to whether a subject can perform certain operations in the application.

Official document: https://docs.spring.io/spring-security/site/docs/5.4.2/reference/html5/#servlet-hello

The complete code of this case: SpringBootSecurity

2. Introduce dependencies

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

3. Write Security configuration class

Control requested access

@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");
        //开启登录功能
        //访问上述请求时,会来到登录页"/login",当请求失败,会来到"/login?error"
        http.formLogin().passwordParameter("pwd").usernameParameter("user").loginPage("/userlogin");

        //开启注销功能
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder() ).withUser("zhangfei").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder() ).withUser("lvbu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder() ).withUser("liubei").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

Note 1: Clear code encryption
Starting from spring security 5.X, you need to use a password encoder, that is, you need to encrypt your plain text password, not without the password encoder NoAppasswordEncoder;
Insert picture description here

Note 2: HttpSecurity
opens the login and logout function

Note 3: security-thymeleaf interaction
Using thymlef's support for security:
Insert picture description here
Need to introduce dependencies:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    <version>3.0.4.RELEASE</version>
</dependency>

Security-thymeleaf namespace constraints:

xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

Use isAuthenticated() to distinguish between logged in and unlogged interfaces:

<div sec:authorize="!isAuthenticated()">
	<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
	<h2><span sec:authentication="name"></span>,您好,您的角色有:<span sec:authentication="principal.authorities"></span></h2>
	<form th:action="@{/logout}" method="post">
		<input type="submit" value="注销"/>
	</form>
</div>

Divide function modules according to roles:

<div sec:authorize="hasRole('vip1')">
	<h3>普通武功秘籍</h3>
	<ul>
		<li><a th:href="@{/level1/1}">罗汉拳</a></li>
		<li><a th:href="@{/level1/2}">武当长拳</a></li>
		<li><a th:href="@{/level1/3}">全真剑法</a></li>
	</ul>
</div>

Note 4: Remember me function After the
login is successful, the cookie will be sent to the browser for saving, and the cookei will be brought with you when you visit in the future, as long as you pass the check, you can log in normally. This cookei will be deleted after clicking logout.

Note 5: We can customize the landing page

http.formLogin().passwordParameter("pwd").usernameParameter("user").loginPage("/userlogin");

//开启记住我功能
http.rememberMe().rememberMeParameter("remember");
<form th:action="@{/userlogin}" method="post">
	用户名:<input name="user"/><br/>
	密码:<input name="pwd"/><br/>
	<input type="checkbox" name="remember"/> 记住我<br/>
	<input type="submit" value="登陆"/>
</form>

Guess you like

Origin blog.csdn.net/glpghz/article/details/112541818