1.认证授权的基础概念
1.1 什么是认证(登录)
进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付宝、头条等,下边拿微信来举例子说明认证相关的基本概念,在初次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微信,输入账号和密码登录微信的过程就是认证。
系统为什么要认证?
http://127.0.0.1:8080/getAllUser
http://127.0.0.1:8080/addUser
http://127.0.0.1:8080/updateUser
http://127.0.0.1:8080/deleteUser
认证是为了保护系统的隐私数据与资源,用户的身份合法方可访问该系统的资源。
认证 :用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源(url接口)时系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。常见的用户身份认证方式有:用户名密码登录,二维码登录,手机短信登录,指纹认证等方式。
1.2 什么是会话
HttpSession
SqlSession
用户认证通过后,为了避免用户的每次操作都进行认证可将用户的信息保证在会话中。会话就是系统为了保持当前用户的登录状态所提供的机制,常见的有基于session方式、基于token方式等。
1.2.1 基于session的认证方式
它的交互流程是,用户认证成功后,在服务端生成用户相关的数据保存在session(当前会话)中,发给客户端的sesssion_id 存放到 cookie 中,这样用户客户端请求时带上 session_id 就可以验证服务器端是否存在 session 数据,以此完成用户的合法校验,当用户退出系统或session过期销毁时,客户端的session_id也就无效了
1.2.2 基于token方式认证方式
它的交互流程是,用户认证成功后,服务端生成一个token发给客户端,客户端可以放到 cookie 或 localStorage等存储中,每次请求时带上 token,服务端收到token通过验证后即可确认用户身份。Redis 存的用户信息 共享session (分布式中)
基于session的认证方式由Servlet规范定制,服务端要存储session信息需要占用内存资源,客户端需要支持cookie;基于token的方式则一般不需要服务端存储token,并且不限制客户端的存储方式。如今移动互联网时代更多类型的客户端需要接入系统,系统多是采用前后端分离的架构进行实现,所以基于token的方式更适合。
1.3 什么是授权 (给用户颁发权限)
还拿微信来举例子,微信登录成功后用户即可使用微信的功能,比如,发红包、发朋友圈、添加好友等,没有绑定银行卡的用户是无法发送红包的,绑定银行卡的用户才可以发红包,发红包功能、发朋友圈功能都是微信的资源即功能资源,用户拥有发红包功能的权限才可以正常使用发送红包功能,拥有发朋友圈功能的权限才可以使用发朋友圈功能,这个根据用户的权限来控制用户使用资源的过程就是授权。 鉴权(判断用户是否有这个权限)
java应用中什么叫资源 url就是资源 (API接口就是资源)
http://127.0.0.1:8080/user/getUserById?id=10
1.3.1 为什么要授权?(控制资源(url)被访问)
认证是为了保证用户身份的合法性,授权则是为了更细粒度的对隐私数据进行划分,授权是在认证通过后发生的,控制不同的用户能够访问不同的资源。
授权: 授权是用户认证通过根据用户的权限来控制用户访问资源的过程,拥有资源的访问权限则正常访问,没有权限则拒绝访问。
200
302
400
403
404
1.4 授权的数据模型(RBAC)
如何进行授权即如何对用户访问资源进行控制,首先需要学习授权相关的数据模型。
授权可简单理解为Who对What(which)进行How操作,包括如下:
Who,即主体(Subject),主体一般是指用户,也可以是程序,需要访问系统中的资源。 What,即资源(Resource),如系统菜单、页面、按钮、代码方法、系统商品信息、系统订单信息等。系统菜单、页面、按钮、代码方法都属于系统功能资源,对于web系统每个功能资源通常对应一个URL;系统商品信息、系统订单信息都属于实体资源(数据资源),实体资源由资源类型和资源实例组成,比如商品信息为资源类型,商品编号 为001的商品为资源实例。
How,权限/许可(Permission),规定了用户对资源的操作许可,权限离开资源没有意义,如用户查询权限、用户添加权限、某个代码方法的调用权限、编号为001的用户的修改权限等,通过权限可知用户对哪些资源都有哪些操作可。
主体、资源、权限关系如下图:
主体、资源、权限相关的数据模型如下:
主体(用户id、账号、密码、…)
资源(资源id、资源名称、访问地址、…)
权限(权限id、权限标识、权限名称、资源id、…)
角色(角色id、角色名称、…)
角色和权限关系(角色 id、权限id、…)
主体(用户)和角色关系(用户id、角色id、…)
主体(用户)、资源、权限关系如下图:
通常企业开发中将资源和权限表合并为一张权限表,如下:
资源(资源id、资源名称、访问地址、…)
权限(权限id、权限标识、权限名称、资源id、…)
合并为:
权限(权限id、权限标识、权限名称、资源名称、资源访问地址、…)
修改后数据模型之间的关系如下图:
1.5 RBAC
用户,角色,权限 本质:就是把权限打包给角色,分配给用户
RBAC一般指基于角色的访问控制 权限 五张表 (最少五张表)
基于角色的访问控制(RBAC)是实施面向企业安全策略的一种有效的访问控制方式。
1.5.1 基于角色的访问控制
RBAC基于角色的访问控制(Role-Based Access Control)是按角色进行授权,比如:主体的角色为总经理可以查询企业运营报表,查询员工工资信息等
根据上图中的判断逻辑,授权代码可表示如下:
if(主体.hasRole(“总经理角色id”)){
查询工资
}
如果上图中查询工资所需要的角色变化为总经理和部门经理,此时就需要修改判断逻辑为“判断用户的角色是否是总经理或部门经理”,修改代码如下:
if(主体.hasRole(“总经理角色id”) || 主体.hasRole(“部门经理角色id”)){
查询工资
}
根据上边的例子发现,当需要修改角色的权限时就需要修改授权的相关代码,系统可扩展性差。
1.5.2 基于资源的访问控制
RBAC基于资源的访问控制(Resource-Based Access Control)是按资源(或权限)进行授权,比如:用户必须具有查询工资权限才可以查询员工工资信息等,如下的判断
if(主体.hasPermission(“查询工资”) ){
查询工资
}
优点:系统设计时定义好查询工资的权限标识,即使查询工资所需要的角色变化为总经理和部门经理也不需要修改授权代码,系统可扩展性强。
2.Spring Security 简介
官网: https://spring.io/projects/spring-security
中文文档: https://www.springcloud.cc/spring-security.html
2.1 什么是SpringSecurity
Spring Security是一个能够为基于Spring的企业应用系统提供声明式(注解)的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
以上解释来源于百度百科。可以一句话来概括,SpringSecurity 是一个安全框架。
3.Spring Security入门体验
3.1 创建父项目spring-security-main
把下面的项目都放在这个项目里面,方便展示和学习
3.2 创建项目security-hello并且选择依赖
3.3 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bjpowernode</groupId>
<artifactId>01-security-hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>security-hello</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.4 启动类
@SpringBootApplication
@EnableWebSecurity // 启用security 在5.X版本之后可以不用加,默认就是开启的
public class SecurityHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityHelloApplication.class, args);
}
}
3.5 创建HelloController
@RestController
public class HelloController {
@GetMapping("hello")
public String hello() {
return "hello security";
}
}
3.6 启动测试访问
http://127.0.0.1:8080/hello
发现我们无法访问hello这个请求,这是因为spring Security默认拦截了所有请求
使用user+启动日志里面的密码登陆
登录后就可以访问我们的hello了
3.7 测试退出
访问: http://localhost:8080/logout
3.8 自定义密码登录(yml配置文件方式)
spring:
security:
user:
name: admin #默认使用的用户名
password: 123456 #默认使用的密码
3.9 重启使用admin和123456登录即可
3.10 总结
从上面的体验来说,是不是感觉很简单,但是别急。后面的东西还是有点难度的,如下:
l 如何读取数据库的用户名和密码
l 如何对密码加密
l 如何使用数据库的角色和权限
l 如何配置方法级别的权限访问
l 如何自定义登陆页面
l 如何集成redis把登陆信息放到Redis
l 如何集成验证码
l ……………………
4.Spring Security配置多用户认证
4.1 概述
认证就是登陆,我们现在没有连接数据库,那么我们可以模拟下用户名和密码
4.2 创建认证的配置类WebSecurityConfig
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户信息,模拟内存用户数据
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置两个用户
auth.inMemoryAuthentication()
.withUser("cxs")
.password("123")
.roles("ADMIN")
.and()
.withUser("test")
.password("123")
.roles("TEST");
}
}
4.3 启动测试
我们只要添加了安全配置类,那么我们在yml里面的配置就失效了
我们使用cxs/123访问登录,发现控制台报错了
这个是因为spring Sercurity强制要使用密码加密,当然我们也可以不加密,但是官方要求是不管你是否加密,都必须配置一个类似Shiro的凭证匹配器
4.4 修改WebSecurityConfig添加加密器
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户信息,模拟内存用户数据
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置两个用户
auth.inMemoryAuthentication()
.withUser("cxs")
.password(passwordEncoder().encode("123"))
.roles("ADMIN")
.and()
.withUser("test")
.password(passwordEncoder().encode("123"))
.roles("TEST");
}
/*
* 从 Spring5 开始,强制要求密码要加密
* 如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,
* 但是不建议这么做,毕竟不安全。
*
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
4.5 重启测试
两个用户都可以登录成功了
4.6 测试加密和解密
我们对123字符串加密三次,然后匹配三次,看看效果
public class TestPasswordEncoder {
public static void main(String[] args) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String encode1 = passwordEncoder.encode("123");
System.out.println(encode1);
String encode2 = passwordEncoder.encode("123");
System.out.println(encode2);
String encode3 = passwordEncoder.encode("123");
System.out.println(encode3);
// 查看加密后是否匹配
System.out.println(passwordEncoder.matches("123", encode1));
System.out.println(passwordEncoder.matches("123", encode2));
System.out.println(passwordEncoder.matches("123", encode3));
}
}
查看控制台发现特点是:相同的字符串加密之后的结果都不一样,但是比较的时候是一样的
4.7 如何获取当前登录用户的信息(两种方式)【重点】
我们添加获取当前用户信息的Controller
/**
* 获取当前用户信息,直接在参数中注入Principal对象
* 此对象是登录后自动写入UsernamePasswordAuthenticationToken类中
*
* @param principal
* @return
*/
@GetMapping("userInfo")
public Principal getUserInfo(Principal principal) {
return principal;
}
/**
* SecurityContextHolder.getContext()获取安全上下文对象
* 就是那个保存在 ThreadLocal 里面的安全上下文对象
* 总是不为null(如果不存在,则创建一个authentication属性为null的empty安全上下文对象)
* 获取当前认证了的 principal(当事人),或者 request token (令牌)
* 如果没有认证,会是 null,该例子是认证之后的情况
*/
@GetMapping("userInfo2")
public Object getUserInfo2() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication;
}
测试访问
http://localhost:8080/userInfo
http://localhost:8080/userInfo2
5.Spring Security用户,角色,权限拦截配置
5.1 角色和权限的配置,修改WebSecurityConfig类
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置用户信息,模拟内存用户数据
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置几个用户
auth.inMemoryAuthentication()
.withUser("cxs")
.password(passwordEncoder().encode("123"))
.roles("ADMIN")
.authorities("sys:save", "sys:del", "sys:update", "sys:query") // 给cxs用户添加四个权限
.and()
.withUser("test")
.password(passwordEncoder().encode("123"))
.roles("TEST")
.authorities("sys:save", "sys:query") // 给test这个用户加两个权限
.and().withUser("admin")
.password(passwordEncoder().encode("123"))
.roles("ADMIN"); // 给admin这个用户一个ADMIN的角色,如果角色和权限都给了,那么角色就失效了
}
/**
* 配置http请求验证等
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// 注释掉他自己的方法 走我们自己的
// super.configure(http);
// 给一个表单登陆 就是我们的登录页面,登录成功或者失败后走我们的url
http.formLogin().successForwardUrl("/welcome").failureForwardUrl("/fail");
// 匹配哪些url,需要哪些权限才可以访问 当然我们也可以使用链式编程的方式
http.authorizeRequests()
.antMatchers("/query").hasAnyAuthority("sys:query")
.antMatchers("/save").hasAnyAuthority("sys:save")
.antMatchers("/del").hasAnyAuthority("sys:del")
.antMatchers("/update").hasAnyAuthority("sys:update")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated(); // 其他所有的请求都需要登录才能进行
}
/*
* 从 Spring5 开始,强制要求密码要加密
* 如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,
* 但是不建议这么做,毕竟不安全。
*
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
5.2 添加几个Controller接口
/**
* 登录成功后的欢迎页面
*
* @return
*/
@PostMapping("welcome")
public String welcome() {
return "我是登录成功后的欢迎页面welcome";
}
@GetMapping("save")
public String save() {
return "我是save页面";
}
@GetMapping("del")
public String del() {
return "我是del页面";
}
@GetMapping("update")
public String update() {
return "我是update页面";
}
@GetMapping("query")
public String query() {
return "我是query页面";
}
@GetMapping("admin/hello")
public String admin() {
return "我是只有admin角色才可以访问的";
}
5.3 启动测试
使用cxs/123登录后 这几个接口都可以访问
使用test/123登录后,访问/update和/del会报错跳到403页面
使用admin/123登录后,只能访问/admin/hello,访问其他接口会跳到403页面
5.4 我们添加一个403.html,让他报错后跳到我们自己的页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>403页面</title>
</head>
<body>
<h2>403:你没有权限访问此页面</h2>
</body>
</html>
5.5 重启使用test登录后访问/del
6.Spring Security方法级别的授权(鉴权)
我们使用方法级别的授权后,只需要在controller对应的方法上添加注解即可了,不需要再webSecurityConfig中配置匹配的url和权限了,这样就爽多了
6.1 相关注解说明
@PreAuthorize 在方法调用前进行权限检查
@PostAuthorize 在方法调用后进行权限检查
上面的两个注解如果要使用的话必须加上
@EnableGlobalMethodSecurity(prePostEnabled = true)
如果只使用PreAuthorize 就只用开启prePostEnabled = true
6.2 在WebSecurityConfig类上添加注解
6.3 注释掉WebSecurityConfig配置url和权限的代码
6.4 修改controller,给方法添加注解
不加注解的,都可以访问,加了注解的,要有对应权限才可以访问哦
@GetMapping("save")
@PreAuthorize("hasAuthority('sys:save')")
public String save() {
return "我是save页面";
}
@GetMapping("del")
@PreAuthorize("hasAuthority('sys:del')")
public String del() {
return "我是del页面";
}
@GetMapping("update")
@PreAuthorize("hasAuthority('sys:update')")
public String update() {
return "我是update页面";
}
@GetMapping("query")
@PreAuthorize("hasAuthority('sys:query')")
public String query() {
return "我是query页面";
}
6.5 重启测试即可
7.Spring Security返回JSON(前后端分离)
在上面的例子中,我们返回的是403页面,但是在开发中,如RestAPI风格的数据,是不能返回一个页面,而应该是给一个json
7.1 创建Result
package com.powernode.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
private Integer code;
private String msg;
private Object data;
public Result(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
7.2 创建登陆成功的处理器AppAuthenticationSuccessHandler
package com.powernode.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.common.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 登陆成功的处理器
* 要求返回JSON
*/
@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//声明一个把对象转成JSON的对象
private ObjectMapper objectMapper=new ObjectMapper();
/**
*
* @param request 当前的请求对象
* @param response 当前的响应对象
* @param authentication 认证成功之后的身份对象
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
System.out.println("登陆成功");
//设置响应编码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
//返回JSON出去
Result result=new Result(200,"登陆成功",authentication);
//把result转成JSON
String json = objectMapper.writeValueAsString(result);
//响应出去
PrintWriter out = response.getWriter();
out.write(json);
out.flush();
}
}
7.3 创建登陆失败处理器AppAuthenticationFailureHandler
package com.powernode.handler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.common.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 登陆失败的处理器
*/
@Component
public class AppAuthenticationFailureHandler implements AuthenticationFailureHandler {
//声明一个把对象转成JSON的对象
private ObjectMapper objectMapper=new ObjectMapper();
/**
* @param request 当前的请求对象
* @param response 当前的响应对象
* @param exception 失败的原因的异常
* @throws IOException
* @throws ServletException
*/
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.err.println("登陆失败");
//设置响应编码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
//返回JSON出去
Result result=new Result(-1,"登陆失败");
if(exception instanceof BadCredentialsException){
result.setData("密码不正确");
}else if(exception instanceof DisabledException){
result.setData("账号被禁用");
}else if(exception instanceof UsernameNotFoundException){
result.setData("用户名不存在");
}else if(exception instanceof CredentialsExpiredException){
result.setData("密码已过期");
}else if(exception instanceof AccountExpiredException){
result.setData("账号已过期");
}else if(exception instanceof LockedException){
result.setData("账号被锁定");
}else{
result.setData("未知异常");
}
//把result转成JSON
String json = objectMapper.writeValueAsString(result);
//响应出去
PrintWriter out = response.getWriter