SpringBoot——安全

一、Spring Security

1、基本概念

两个安全框架:shiro、Spring Security

Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅需引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

应用程序在处理安全问题的两个主要领域是“认证”和“授权”(访问控制):

  • “认证”(Authentication):主要是指通过用户名/密码来验证主体的过程。
  • “授权”(Authorization):指一个主体是否可以在应用中执行某些操作。

官方文档:https://docs.spring.io/spring-security/site/docs/5.4.2/reference/html5/#servlet-hello

本案例完整代码:SpringBootSecurity

2、引入依赖

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

3、编写Security配置类

控制请求的访问权限

@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");
    }
}

注意点1:明码加密
从spring security 5.X开始,需要使用密码编码器,也就是需要对你的明文密码进行加密,而不能没有密码编码器NoAppasswordEncoder;
在这里插入图片描述

注意点2:HttpSecurity
开启登录注销功能

注意点3:security-thymeleaf交互
利用thymlef对security的支持:
在这里插入图片描述
需要引入依赖:

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

security-thymeleaf命名空间约束:

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

使用isAuthenticated()将登录和未登录的界面进行区分:

<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>

根据角色划分功能模块:

<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>

注意点4:记住我功能
登录成功以后将cookie发送给浏览器进行保存,以后访问时会带上这个cookei,只要通过检查就能够正常登录了。点击注销后就会删除这个cookei。

注意点5:我们可以定制登陆页面

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>

猜你喜欢

转载自blog.csdn.net/glpghz/article/details/112541818