SpringBoot(5)-SpringSecurity

目录

一、是什么

二、实战测试

2.1 认识

2.2 认证和授权

2.3 权限控制和注销

2.4 记住我


一、是什么

Spring Security是一个框架,侧重于为java应用程序提供身份验证和授权。

Web应用的安全性主要分为两个部分:

认证(Authentication)和授权(Authorization)

  •  “认证”(Authentication):验证用户的凭证,如用户名和密码等
  • “授权”(Authorization):在系统验证用户身份后,会授予访问资源的权限

二、实战测试

准备工作:

1、新建一个springboot项目web模块,导入thymeleaf依赖

2、导入静态资源

3、编写controller

4、测试

2.1 认识

Spring Security是针对Spring项目的安全框架,我们仅需要引入spring-boot-starter-security模块,进行少量配置,即可实现强大的安全管理!

其中的重要类有:

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

2.2 认证和授权

1、引入Spring Security 模块

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

2、编写Spring Security 配置类

①授权:重写configure(HttpSecurity http)方法

 

②认证:重写configure(AuthenticationManagerBuilder auth)方法

注意!如果不将前端传来的密码进行某种方式加密,就会报错:There is no PasswordEncoder mapped for the id “null” 

spring security 官方推荐的是使用bcrypt加密方式 

3、测试

2.3 权限控制和注销

 1、开启自动配置的注销功能

2、前端:增加一个注销的按钮,index.html 导航栏中

3、默认注销完毕后跳转到登录页面,若我们想实现注销完跳转到首页

4、测试 

需求:

  1. 用户没有登录时,导航栏只显示登录按钮; 
  2. 用户登录后,导航栏显示登录的用户信息及注销按钮
  3. 以及,只显示用户有打开权限的功能

1、需要结合thymeleaf实现,所以要导入thymeleaf和spring security整合的依赖

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

 2、前端

首先导入命名空间

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

增加认证判断

 

3、测试

2.4 记住我

 实现功能:登录时点击“记住我”,这样登录之后,关闭浏览器,再打开,不需要重新登陆

1、开启记住我功能(本质就是保存了cookie)

2、前端

 

3、测试

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值