Spring Boot 框架学习笔记(五)

  • SpringSecurity安全框架
    • 概述
      • 作用
    • 开发示例:
      • 1. 新建项目
      • 2. 引入依赖
      • 3. 编写`SecurityConfig`类,实现认证,授权,注销
      • 4. 菜单权限
      • 5. 测试

SpringSecurity安全框架

概述

跟随该b站视频练习
代码地址

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

记住几个类(通用):

  • WebSecurityConfigurerAdapter:自定义Security策略(我们需要继承这个类)

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

作用

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)

  • “认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

  • “授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在

开发示例:

@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值

1. 新建项目

2. 引入依赖

 <!--security--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!--web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--thymeleaf模板--><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-java8time</artifactId></dependency>

3. 编写SecurityConfig类,实现认证,授权,注销

  • http.formLogin():没有权限默认跳回登录页面
  1. 源码中跳转登录页的说明:
    The most basic configuration defaults to automatically generating a login page at the URL "/login", redirecting to "/login?error" for authentication failure.
  2. 源码中认证示例:
protected void configure(AuthenticationManagerBuilder auth) throws Exception { *        auth.inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;);     *  }
  1. 源码中注销示例:可删除内存保存的信息
  • logoutUrl:指定的注销需要访问的地址
  • logoutSuccessUrl:注销成功跳转的地址
@Override
protected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin()
.and()
// sample logout customization              .logout().deleteCookies(&quot;remove&quot;).invalidateHttpSession(false)                .logoutUrl(&quot;/custom-logout&quot;).logoutSuccessUrl(&quot;/logout-success&quot;);   }
/*AOP拦截器*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter  {//授权@Overrideprotected void configure(HttpSecurity http) throws Exception {//首页所有人可访问,但是功能页需要权限分类http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasAnyRole("vip2","vip1").antMatchers("/level3/**").hasAnyRole("vip3","vip2","vip1");//没有权限默认跳回登录页面http.formLogin();//防止网站工具(post,get)http.csrf().disable();//开启注销功能,注销成功返回首页http.logout().logoutSuccessUrl("/");//开启记住我功能,就是cookie,默认保存两周http.rememberMe();}//认证@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//在内存读取用户认证(多个用户用”and“连接)auth.inMemoryAuthentication().withUser("yeyu").password("1234").roles("vip2","vip3").and().withUser("yuese").password("5678").roles("vip1");}
}
  • 可以去数据库中认证:auth.jdbcAuthentication(),官方文档示例:
@Autowired
private DataSource dataSource;@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema().withUser("user").password("password").roles("USER").and().withUser("admin").password("password").roles("USER", "ADMIN");
}
  • 可以在内存中认证:auth.inMemoryAuthentication()

注意:此处springboot版本高的话会报There is no PasswordEncoder mapped for the id "null"错误,所以需要对密码加密:

 //认证@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//在内存读取用户认证(多个用户用”and“连接)auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("yeyu").password(new BCryptPasswordEncoder().encode("1234")).roles("vip2","vip3").and().withUser("yuese").password(new BCryptPasswordEncoder().encode("5678")).roles("vip1");}

4. 菜单权限

这个时候发现不同权限看到的菜单依旧一样,所以引入thymeleaf-security整合包:

  • 引入依赖
 <!-- thymeleaf-springsecurity整合 --><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity4</artifactId><version>3.0.4.RELEASE</version></dependency>
  • 引入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
  • index代码:
  <!--判断用户是否登录--><!--如果未登录,显示登陆页面--><div sec:authorize="!isAuthenticated()"><a class="item" th:href="@{/toLogin}" ><i class="address card icon"></i> 登录</a></div><!--如果登录:显示用户名,注销按钮--><div sec:authorize="isAuthenticated()"><a class="item" >用户名:<span sec:authentication="name"></span>角色:<span sec:authentication="principal.getAuthorities()"></span></a></div><div sec:authorize="isAuthenticated()"><a class="item" th:href="@{/logout}" ><i class="address card icon"></i> 注销</a></div>

5. 测试


Spring Boot 框架学习笔记(五)( SpringSecurity安全框架 )相关推荐

  1. Spring Boot 2 学习笔记(2 / 2)

    Spring Boot 2 学习笔记(1 / 2) - - - 45.web实验-抽取公共页面 46.web实验-遍历数据与页面bug修改 47.视图解析-[源码分析]-视图解析器与视图 48.拦截器 ...

  2. Spring Boot基础学习笔记15:实现文件下载功能

    文章目录 零.学习目标 一.文件下载概述 二.实现文件下载功能 (一)创建Spring Boot项目 (二)整合Bootstrap (三)准备待下载文件 (四)编写文件下载页面 (五)编写文件下载控制 ...

  3. Spring Boot基础学习笔记14:实现文件上传功能

    文章目录 零.学习目标 一.文件上传概述 二.实现文件上传功能 (一)创建Spring Boot项目 (二)整合Bootstrap (三)编写文件上传页面 (四)编写项目配置文件 (五)编写文件上传控 ...

  4. Spring Boot基础学习笔记20:Spring Security入门

    文章目录 零.学习目标 一.Spring Security (一)Spring Security概述 (二)Spring Boot整合Spring Security实现的安全管理功能 二.基础环境搭建 ...

  5. Spring Boot基础学习笔记19:自定义RedisTemplate与RedisCacheManager

    文章目录 零.学习目标 一.为什么要采用自定义Redis缓存序列化机制 二.自定义RedisTemplate (一)Redis API 默认序列化机制 (二)自定义RedisTemplate序列化机制 ...

  6. Spring Boot基础学习笔记18:Spring Boot整合Redis缓存实现

    文章目录 零.学习目标 一.Spring Boot支持的缓存组件 二.基于注解的Redis缓存实现 (一)安装与启动Redis (二)创建Spring Boot项目 - RedisCacheDemo0 ...

  7. Spring Boot基础学习笔记17:Spring Boot默认缓存

    文章目录 零.学习目标 一.缓存概述 (一)引入缓存管理的重要性 (二)Spring Boot的缓存管理 二.Spring Boot默认缓存 (一)数据准备 (二)创建Spring Boot项目 - ...

  8. Spring Boot基础学习笔记16:项目打包部署

    文章目录 零.学习目标 一.Web项目打包部署概述 二.Jar包方式打包部署 (一)添加Maven打包插件 (二)使用IDEA进行打包 (三)Jar包目录结构说明 (四)Jar包方式部署 1.在控制台 ...

  9. Spring Boot基础学习笔记13:路径扫描整合Servlet三大组件

    文章目录 零.学习目标 一.创建Spring Boot项目 - IntegrateThreeComponents02 二.使用路径扫描方式整合Servlet三大组件 (一)创建MyServlet类 ( ...

最新文章

  1. 自己动手实现OpenGL之glViewPort(一)
  2. python博弈论代码_使用 40 多行的 Python 代码实现一个简单的演化过程
  3. 专访福建移动林志云: 5G使能,运营商全面进入数字化转型之路
  4. hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
  5. Tortoise SVN 汉化(官网下载汉化包)
  6. Arcgis字段计算器实现自动编码
  7. 若依 数据权限图文详细理解及改造
  8. nvidia卸载程序失败_英伟达显卡驱动安装失败怎么办?
  9. 网易云音乐编码_为什么有那么多编码员音乐家?
  10. 如何在uni-app中使用vant组件?最细教学,还看不懂你来捶我
  11. D38 463. Island Perimeter
  12. 什么是Kodu---Kodu少儿编程第一天
  13. 1.设计一个长方形的类,成员变量有长与宽,成员函数有求周长与面积,然后进行测试。要求有构造函数、析造函数和复制构造函数。
  14. Vue 2.爷爷点击事件触发孙子的方法
  15. arm解锁 j-flash_J-Link固件烧录以及使用J-Flash向arm硬件板下载固件程序(示例代码)...
  16. Mysql的索引、视图、触发器、存储过程
  17. Aura component cache clear set
  18. 指点迷津 北大教授告诉你什么是 C语言!
  19. API、SDK是什么
  20. HEU_KMS_Activator_v11.1.0

热门文章

  1. JavaDay13 抽象类 、接口、多态
  2. 玩转外贸LinkedIn必备的三大特质,以及突破六度人脉技巧
  3. Python 办公效率化学习(自学)三.Excel文件读取
  4. 横向数据(按行)的最大值和最小值的SQL语句的编写 !
  5. 分享66个ASP上传下载源码,总有一款适合您
  6. Unity(入门、中级、中高级、高级)
  7. Android 屏幕旋转的处理
  8. Java(等级划分)
  9. php 自定义排序,thinkphp6.0自定义排序order by field
  10. JavaScript的全局作用域、全局对象window