根据“狂神说”教学视频+“狂神说”公众号内容 进行的笔记记录
简介
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。
Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求
实战
1. 创建一个SpringBoot项目
导入web、thymeleaf依赖
2. 引入静态资源
index.html
|views
|level1
1.html
2.html
3.html
|level2
1.html
2.html
3.html
|level3
1.html
2.html
3.html
Login.html
3. 创建Controller
@Controller
public class RouterController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping("/login")
public String login(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/" + id;
}
@RequestMapping("/level2/{id}")
public String levle2(@PathVariable("id") int id){
return "views/level2/" + id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/" + id;
}
}
4. 测试
初始Spring Security
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
WebSecurityConfigurerAdapter:自定义Security策略
AuthenticationManagerBuilder:自定义认证策略
@EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
“认证”(Authentication)
身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
== “授权” (Authorization)==
授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
这个概念是通用的,而不是只在Spring Security 中存在。
授权 和 认证
1. 导入依赖
<!--导入security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 编写SprinSecurity配置类
官网:https://docs.spring.io/spring-security/site/docs/5.3.2.RELEASE/reference/html5/
//继承WebSecurityAdapter类
@EnableWebSecurity //开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}
3. 定制请求授权规则
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问
//其余页面需要指定角色访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
}
4. 测试
我们发现除了首页其余页面都无法进入 http status = 403
可以看出是因为权限不足
5. 自动跳转登录功能
在请求授权的方法中添加下面代码
//权限不足,跳转login页面
//定制登录页面
http.formLogin().loginPage("/login").
usernameParameter("user").
passwordParameter("pwd");
formLogin() 表示权限不足会跳转到springsecurity默认的login页面
loginPage("xxx") 表示 权限不足 跳转到指定的xxx请求下
usernameParameter("xxx") 表示 接收客户端的用户名参数name的值为xxx
passwordParameter("xxx") 表示 接收客户端的密码参数name的值为xxx
用户名和密码是需要在“认证”中定义 我们下面会介绍 先记起来
6. 测试
测试发现 访问被请求授权的请求 会直接跳转到login页面
7. 定制授权认证规则
我们上方定义了授权 在没有权限的情况下访问指定页面会跳转到login
我们这里可以自定义认证规则 也就是赋予权限
重写configure(AuthenticationManagerBuilder auth)方法
//认证
//密码编码:PasswordEncoder
//Spring Security 5.x版本后 密码需要加密 为了安全性
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("liuhao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
}
}
inMemoryAuthentication() 内存身份验证
【auth.jdbcAuthentication()】 也可以从jdbc中获取
passwordEncoder(new BCryptPasswordEncoder())
密码加密 使用springsecurity推荐的BCryptPasswordEncoder
withUser("guest") 认证登陆的用户名
password(new BCryptPasswordEncoder().encode("123456"))
认证登录的密码 进行了加密操作new BCryptPasswordEncoder().encode("123456")
roles("vip1") 认证的角色 在请求授权时我们定义了指定角色才能访问指定页面
8. 测试
测试发现登录成功,并且每个角色只能访问自己认证下的规则
权限控制 和 注销
1. 开启注销功能
在授权方法下 加入以下代码
//注销 跳转到首页
@Override
protected void configure(HttpSecurity http) throws Exception {
http.logout().logoutSuccessUrl("/");
}
logout() 开启自动配置注销功能 注销后跳转到 logout请求
logoutSuccessUrl() 注销成功后跳转到的页面
2. 前端添加注销按钮
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
3. 测试
测试发现 我们在每加.logoutSuccessUrl("xxx")这个方法前
注销后会跳转到login页面
加上后就会跳转到 我们指定的xxx请求下了
【4. 给前端增加一些小功能】
增加功能: 未登录时显示登录按钮 登录之后显示用户名、注销按钮
需要结合thymeleaf模板引擎支持
导入依赖
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
前端代码
<!--未登录-->
<div sec:authorize="!isAuthenticated()"></div>
<a class="item" th:href="@{/login}">
<i class="address card icon"></i> 登录
</a>
<!--已登录 注销-->
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
用户名:<span sec:authentication="principal.username"></span>
角色:<span sec:authentication="principal.authorities"></span>
</a>
</div>
测试访问
如果出现404 在配置中加入以下代码
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
http.logout().logoutSuccessUrl("/");
记住我
在配置类加入以下代码
//记住我
http.rememberMe().rememberMeParameter("remember");
rememberParameter("xxx") 前端的name参数
前端页面
<div class="field">
<input type="checkbox" name="remember">记住我
</div>
完整配置
package com.it.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@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页面
//定制登录页面
http.formLogin().loginPage("/login").usernameParameter("user").passwordParameter("pwd");
http.csrf().disable();
//注销 跳转到首页
http.logout().logoutSuccessUrl("/");
//记住我
http.rememberMe().rememberMeParameter("remember");
}
//认证
//密码编码:PasswordEncoder
//Spring Security 5.x版本后 密码需要加密 为了安全性
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("liuhao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
}
}