SpringSecurity
来源视频
文章目录
- SpringSecurity
- 1、概述
- 2、Spring Security、Apache Shiro 选择问题
- 2.1、Shiro
- 2.1.1、shiro的优点
- 2.1.2、shiro的缺点
- 2.2、Spring Security
- 2.2.1、spring-security的优点
- 3、快速入门
- 3.1、装备工作
- 4、认证
- 4.1、登录流程校验
- 4.2、入门案例的原理
- 4.3、正式开始
- 4.3.1 准备工作
- 4.3.2、实现
- 4.3.3、核心代码实现
- 4.3.3.1、密码加密存储
- 4.3.3.2、登陆接口
- 4.3.3.3、认证过滤器
- 4.3.3.4、退出登陆
- 5、授权
- 5.1、权限的作用
- 5.2、授权基本流程
- 5.3、授权实现
- 5.3.1、限制访问资源所需权限
- 5.3.2、封装权限信息
- 5.3.3 从数据库查询权限信息
- 5.3.3.1 RBAC权限模型
- 5.3.3.2 准备工作
- 5.3.3.3、代码实现
- 6、自定义失败处理
- 6.1、自定义实现类
- 6.2、配置给SpringSecurity
- 7、 跨域
- 8、自定义权限校验方法
- 9、CSRF
- 10、认证处理器
- 10.1、认证成功处理器
- 10.2、认证失败处理器
- 10.3、注销成功处理器
- 彩蛋:
1、概述
Spring Security是 Spring 家族中的一个安全管理框架。相比与另外一个安全框架Shiro,它提供了更丰富的功能,社区资源也比Shiro丰富;
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架
。它是用于保护基于Spring的应用程序的实际标准;
Spring Security是一个框架,致力于为Java应用程序提供身份验证和授权
。与所有Spring项目一样,Spring Security的真正强大之处在于可以轻松扩展以满足自定义
要求。
在 Java 生态中,目前有 Spring Security 和 Apache Shiro 两个安全框架,可以完成认证和授权的功能。
我们先来学习下 Spring Security 。其官方对自己介绍如下:
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的事实标准。
Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirementsSpring
Security是一个专注于为Java应用程序提供身份验证和授权的框架。与所有Spring项目一样,Spring Security的真正威力在于它可以多么容易地扩展以满足定制需求
一般Web应用的需要进行认证和授权。
认证(Authentication):验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户
授权(Authorization):经过认证后判断当前用户是否有权限进行某个操作
而认证和授权就是SpringSecurity作为安全框架的核心功能。
2、Spring Security、Apache Shiro 选择问题
2.1、Shiro
首先Shiro较之 Spring Security,Shiro在保持强大功能的同时,还在简单性和灵活性方面拥有巨大优势。
Shiro是一个强大而灵活的开源安全框架,能够非常清晰的处理认证、授权、管理会话以及密码加密。如下是它所具有的特点:
易于理解的 Java Security API;
简单的身份认证(登录),支持多种数据源(LDAP,JDBC,Kerberos,ActiveDirectory 等);
对角色的简单的签权(访问控制),支持细粒度的签权;
支持一级缓存,以提升应用程序的性能;
内置的基于 POJO 企业会话管理,适用于 Web 以及非 Web 的环境;
异构客户端会话访问;
非常简单的加密 API;
不跟任何的框架或者容器捆绑,可以独立运行。
Shiro四大核心功能:Authentication,Authorization,Cryptography,Session Management
四大核心功能介绍:
- Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
- Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
- Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的;
- Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
Shiro架构
Shiro三个核心组件:Subject, SecurityManager 和 Realms.
- Subject:主体,可以看到主体可以是任何可以与应用交互的 用户;
- SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。
- Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。
2.1.1、shiro的优点
- shiro的代码更易于阅读,且使用更加简单;
- shiro可以用于非web环境,不跟任何框架或容器绑定,独立运行;
2.1.2、shiro的缺点
- 授权第三方登录需要手动实现;
2.2、Spring Security
除了不能脱离Spring,shiro的功能它都有。而且Spring Security对Oauth、OpenID也有支持,Shiro则需要自己手动实现。Spring Security的权限细粒度更高,毕竟Spring Security是Spring家族的。
Spring Security一般流程为:
- 当用户登录时,前端将用户输入的用户名、密码信息传输到后台,后台用一个类对象将其封装起来,通常使用的是UsernamePasswordAuthenticationToken这个类。
- 程序负责验证这个类对象。验证方法是调用Service根据username从数据库中取用户信息到实体类的实例中,比较两者的密码,如果密码正确就成功登陆,同时把包含着用户的用户名、密码、所具有的权限等信息的类对象放到SecurityContextHolder(安全上下文容器,类似Session)中去。
- 用户访问一个资源的时候,首先判断是否是受限资源。如果是的话还要判断当前是否未登录,没有的话就跳到登录页面。
- 如果用户已经登录,访问一个受限资源的时候,程序要根据url去数据库中取出该资源所对应的所有可以访问的角色,然后拿着当前用户的所有角色一一对比,判断用户是否可以访问(这里就是和权限相关)。
2.2.1、spring-security的优点
- spring-security对spring整合较好,使用起来更加方便;
- 有更强大的spring社区进行支持;
- 支持第三方的 oauth 授权,官方网站:
在项目中创建一个普通的maven项目
将该普通的maven改为SpringBoot工程
1、添加依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
2、创建启动类
@SpringBootApplicationpublic class IntroductionSpringSecurity { public static void main(String[] args) { SpringApplication.run(IntroductionSpringSecurity.class,args); }}
3、创建Controller
@RestControllerpublic class HelloController { @RequestMapping("/hello") public String hello(){ return "World Hello"; }}
测试访问:
4、导入SpringSecurity依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
重新启动测试:
这时我们可以看到当我们访问我们的接口的时候,就会自动跳转到一个SpringSecurity的默认登陆页面
这时候需要我们登录才可以进行访问
,我们可以看到控制台有一串字符串,其实那就是SpringSecurity初始化生成给我的密码默认用户名:user
输入用户名和密码,再次登录
成功。
4、认证
4.1、登录流程校验
4.2、入门案例的原理
前后端认证流程:
UsernamePasswordAuthenticationFilter:
是我们最常用的用户名和密码认证方式的主要处理类,构造了一个UsernamePasswordAuthenticationToken对象实现类,将用请求信息封装为AuthenticationAuthentication接口: 封装了用户相关信息。
AuthenticationManager接口:定义了认证Authentication的方法,是认证相关的核心接口,也是发起认证的出发点,因为在实际需求中,我们可能会允许用户使用用户名+密码登录,同时允许用户使用邮箱+密码,手机号码+密码登录,甚至,可能允许用户使用指纹登录(还有这样的操作?没想到吧),
所以说AuthenticationManager一般不直接认证
,AuthenticationManager接口的常用实现类ProviderManager 内部会维护一个List列表,存放多种认证方式,实际上这是委托者模式的应用(Delegate)
。也就是说,核心的认证入口始终只有一个:AuthenticationManagerAuthenticationManager,ProviderManager ,AuthenticationProvider…
用户名+密码(UsernamePasswordAuthenticationToken),邮箱+密码,手机号码+密码登录则对应了三个AuthenticationProvider
DaoAuthenticationProvider:用于解析并认证
UsernamePasswordAuthenticationToken
的这样一个认证服务提供者,对应以上的几种登录方式。UserDetailsService接口:Spring Security 会将前端填写的username 传给 UserDetailService.loadByUserName方法。我们只需要从数据库中根据用户名查找到用户信息然后封装为UserDetails的实现类返回给SpringSecurity 即可,自己不需要进行密码的比对工作,密码比对交由SpringSecurity处理。
UserDetails接口:提供核心用户信息。通过UserDetailsService根据用户名获取处理的用户信息要封装成UserDetails对象返回。然后将这些信息封装到Authentication对象中。
UsernamePasswordAuthenticationFilter:
是我们最常用的用户名和密码认证方式的主要处理类,构造了一个UsernamePasswordAuthenticationToken对象实现类,将用请求信息封装为AuthenticationBasicAuthenticationFilter...:
将UsernamePasswordAuthenticationFilter的实现类UsernamePasswordAuthenticationToken封装成的 Authentication进行登录逻辑处理AuthenticationManager
AuthenticationProvider
…
UsernamePasswordAuthenticationToken(Authentication的一个实现)对象,其实就是一个Authentication的实现,他封装了我们需要的认证信息。之后会调用AuthenticationManager。这个类其实并不会去验证我们的信息,信息验证的逻辑都是在AuthenticationProvider里面,而Manager的作用则是去管理Provider,管理的方式是通过for循环去遍历(因为不同的登录逻辑是不一样的,比如表单登录、第三方登录(qq登录,邮箱登录…)。换句话说 不同的Provider支持的是不同的Authentication)。在AuthenticationManager调用DaoAuthenticationProvider。而DaoAuthenticationProvider继承了AbstractUserDetailsAuthenticationProvider ,从而也就获得了其中的authenticate方法去进行验证。
[]: https://zhuanlan.zhihu.com/p/201029977
ExceptionTranslationFilter:
主要用于处理AuthenticationException(认证)和AccessDeniedException(授权)的异常FilterSecurityInterceptor:
获取当前 request 对应的权限配置**,**调用访问控制器进行鉴权操作4.3、正式开始
登录:
1.自定义登录接口
调用ProviderManager的方法进行认证 如果认证通过生成jwt
把用户信息存入redis中
2.自定义UserDetailsService
在这个实现类中去查询数据库
校验:
1.定义Jwt认证过滤器
获取token
解析token获取其中的userid
从redis中获取用户信息
存入SecurityContextHolder
4.3.1 准备工作
重新建立一个新的普通maven项目
1.添加依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.79</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies>
2.在主启动类同级目录下建立utils包
添加Redis相关配置
FastJsonRedisSerializer
package com.qx.utils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.serializer.SerializerFeature;import com.fasterxml.jackson.databind.JavaType;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.type.TypeFactory;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.SerializationException;import com.alibaba.fastjson.parser.ParserConfig;import org.springframework.util.Assert;import java.nio.charset.Charset;/** * Redis使用FastJson序列化 */public class FastJsonRedisSerializer<T> implements RedisSerializer<T>{ public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T> clazz; static { ParserConfig.getGlobalInstance().setAutoTypeSupport(true); } public FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz); } protected JavaType getJavaType(Class<" />
5.3.3.2 准备工作
sql
sys_menu:权限表
sys_role:角色表
sys_role_menu:角色权限表
sys_user_role:用户角色表
sys_user:用户表
以便于我们后续使用sys_user连接到sys_user_role表,sys_user_role连接到sys_role表获取用户的角色,sys_role表连接到sys_role_menu表,最终获得用户拥有什么权限
sys_user:
sys_user_role:
sys_role:
sys_role_menu:
sys_menu:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`sg_security` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;USE `sg_security`;/*Table structure for table `sys_menu` */DROP TABLE IF EXISTS `sys_menu`;CREATE TABLE `sys_menu` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '菜单名', `path` varchar(200) DEFAULT NULL COMMENT '路由地址', `component` varchar(255) DEFAULT NULL COMMENT '组件路径', `visible` char(1) DEFAULT '0' COMMENT '菜单状态(0显示 1隐藏)', `status` char(1) DEFAULT '0' COMMENT '菜单状态(0正常 1停用)', `perms` varchar(100) DEFAULT NULL COMMENT '权限标识', `icon` varchar(100) DEFAULT '#' COMMENT '菜单图标', `create_by` bigint(20) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `update_by` bigint(20) DEFAULT NULL, `update_time` datetime DEFAULT NULL, `del_flag` int(11) DEFAULT '0' COMMENT '是否删除(0未删除 1已删除)', `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';/*Table structure for table `sys_role` */DROP TABLE IF EXISTS `sys_role`;CREATE TABLE `sys_role` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(128) DEFAULT NULL, `role_key` varchar(100) DEFAULT NULL COMMENT '角色权限字符串', `status` char(1) DEFAULT '0' COMMENT '角色状态(0正常 1停用)', `del_flag` int(1) DEFAULT '0' COMMENT 'del_flag', `create_by` bigint(200) DEFAULT NULL, `create_time` datetime DEFAULT NULL, `update_by` bigint(200) DEFAULT NULL, `update_time` datetime DEFAULT NULL, `remark` varchar(500) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';/*Table structure for table `sys_role_menu` */DROP TABLE IF EXISTS `sys_role_menu`;CREATE TABLE `sys_role_menu` ( `role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID', `menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '菜单id', PRIMARY KEY (`role_id`,`menu_id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;/*Table structure for table `sys_user` */DROP TABLE IF EXISTS `sys_user`;CREATE TABLE `sys_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名', `nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '昵称', `password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '密码', `status` char(1) DEFAULT '0' COMMENT '账号状态(0正常 1停用)', `email` varchar(64) DEFAULT NULL COMMENT '邮箱', `phonenumber` varchar(32) DEFAULT NULL COMMENT '手机号', `sex` char(1) DEFAULT NULL COMMENT '用户性别(0男,1女,2未知)', `avatar` varchar(128) DEFAULT NULL COMMENT '头像', `user_type` char(1) NOT NULL DEFAULT '1' COMMENT '用户类型(0管理员,1普通用户)', `create_by` bigint(20) DEFAULT NULL COMMENT '创建人的用户id', `create_time` datetime DEFAULT NULL COMMENT '创建时间', `update_by` bigint(20) DEFAULT NULL COMMENT '更新人', `update_time` datetime DEFAULT NULL COMMENT '更新时间', `del_flag` int(11) DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='用户表';/*Table structure for table `sys_user_role` */DROP TABLE IF EXISTS `sys_user_role`;CREATE TABLE `sys_user_role` ( `user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '用户id', `role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '角色id', PRIMARY KEY (`user_id`,`role_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
查询用户具有什么权限得sql语句:
# 根据userid 查询perms 对应的role和menu 都必须是正常状态select distinct m.perms from sys_user_role urleft join sys_role r on ur.role_id=r.idleft join sys_role_menu rm on ur.role_id=rm.role_idleft join sys_menu m on m.id=rm.menu_idwhere user_id=2and r.status=0and m.status=0
实体类:
Menu
package com.qx.entity;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName;import com.fasterxml.jackson.annotation.JsonInclude;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;import java.util.Date;/** * 菜单表(Menu)实体类 * */@TableName(value="sys_menu")@Data@AllArgsConstructor@NoArgsConstructor@JsonInclude(JsonInclude.Include.NON_NULL)public class Menu implements Serializable { private static final long serialVersionUID = -54979041104113736L; @TableId private Long id; /** * 菜单名 */ private String menuName; /** * 路由地址 */ private String path; /** * 组件路径 */ private String component; /** * 菜单状态(0显示 1隐藏) */ private String visible; /** * 菜单状态(0正常 1停用) */ private String status; /** * 权限标识 */ private String perms; /** * 菜单图标 */ private String icon; private Long createBy; private Date createTime; private Long updateBy; private Date updateTime; /** * 是否删除(0未删除 1已删除) */ private Integer delFlag; /** * 备注 */ private String remark;}
5.3.3.3、代码实现
我们只需要根据用户id去查询到其所对应的权限信息即可。
所以我们可以先定义个mapper,其中提供一个方法可以根据userid查询权限信息。
MenuMapper
package com.qx.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.qx.entity.Menu;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;import java.util.List;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Mapper@Repositorypublic interface MenuMapper extends BaseMapper<Menu> { List<String> selectPermsByUserId(Long userid);}
创建对应的Mapper.xml文件,定义对应的sql语句
MenuMapper.xml<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.qx.mapper.MenuMapper"> <select id="selectPermsByUserId" resultType="java.lang.String"> select distinct m.perms from sys_user_role ur left join sys_role r on ur.role_id = r.id left join sys_role_menu rm on ur.role_id = rm.role_id left join sys_menu m on m.id = rm.menu_id where user_id = #{userid} and r.status = 0 and m.status = 0 </select></mapper>
在application.yml中配置mapperXML文件的位置
spring: datasource: url: jdbc:mysql://localhost:3306/qx_security?characterEncoding=utf-8&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Drivermybatis-plus: mapper-locations: classpath*:/mapper/**/*.xmlserver: port: 8888
然后我们可以在UserDetailsServiceImpl中去调用该mapper的方法查询权限信息封装到LoginUser对象中即可。
package com.qx.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;import com.qx.entity.LoginUser;import com.qx.entity.User;import com.qx.mapper.MenuMapper;import com.qx.mapper.UserMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;import org.springframework.stereotype.Service;import java.util.List;import java.util.Objects;/** * @author : k * @Date : 2022/3/23 * @Desc : */@Servicepublic class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserMapper userMapper; @Autowired private MenuMapper menuMapper; //实现UserDetailsService接口,重写UserDetails方法,自定义用户的信息从数据中查询 @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //(认证,即校验该用户是否存在)查询用户信息 LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>(); queryWrapper.eq(User::getUserName,username); User user = userMapper.selectOne(queryWrapper); //如果没有查询到用户 if (Objects.isNull(user)){ throw new RuntimeException("用户名或者密码错误"); } //TODO (授权,即查询用户具有哪些权限)查询对应的用户信息 //定义一个权限集合// List list = new ArrayList(Arrays.asList("test","admin")); List<String> list = menuMapper.selectPermsByUserId(user.getId()); //把数据封装成UserDetails返回 return new LoginUser(user,list); }}
测试:
package com.qx.controller;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.security.core.parameters.P;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author : k * @Date : 2022/3/23 * @Desc : */@RestControllerpublic class HelloController { @RequestMapping("hello")// @PreAuthorize("hasAnyAuthority('admin','test','system:dept:list')")// @PreAuthorize("hasRole('system:dept:list')") //需要加上前缀ROLE_才能通过// @PreAuthorize("hasAnyRole('admin','system:dept:list')")//需要加上前缀ROLE_才能通过// @PreAuthorize("hasAuthority('system:dept:list111')") public String hello(){ return "hello"; }}
6、自定义失败处理
我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。
在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。
如果是认证过程中出现的异常会被封装成AuthenticationException然后调用
AuthenticationEntryPoint
对象的方法去进行异常处理。 如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用
AccessDeniedHandler
对象的方法去进行异常处理。 所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可。
6.1、自定义实现类
AuthenticationEntryPointImpl
package com.qx.handler;import com.alibaba.fastjson.JSON;import com.qx.controller.ResponseResult;import com.qx.utils.WebUtils;import org.springframework.http.HttpStatus;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author : k * @Date : 2022/3/24 * @Desc : 认证的异常处理类 */@Componentpublic class AuthenticationEntryPointImpl implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户名认证失败请重新登录"); String json = JSON.toJSONString(result); //处理移除 WebUtils.renderString(response,json); }}
AccessDeniedHandlerImpl
package com.qx.handler;import com.alibaba.fastjson.JSON;import com.qx.controller.ResponseResult;import com.qx.utils.WebUtils;import org.springframework.http.HttpStatus;import org.springframework.security.access.AccessDeniedException;import org.springframework.security.web.access.AccessDeniedHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author : k * @Date : 2022/3/24 * @Desc : 授权的异常处理 */@Componentpublic class AccessDeniedHandlerImpl implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(),"您的权限不足"); String json = JSON.toJSONString(result); //处理移除 WebUtils.renderString(response,json); }}
6.2、配置给SpringSecurity
@Autowiredprivate AuthenticationEntryPoint authenticationEntryPoint;@Autowiredprivate AccessDeniedHandler accessDeniedHandler;
接着我们就可以使用HttpSecurity对象的方法去配置。
//配置异常处理器http.exceptionHandling() //认证失败处理器 .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler);
7、 跨域
浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求,默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。
前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。
所以我们就要处理一下,让前端能进行跨域请求。
SpringBoot配置,运行跨域请求
CorsConfig
package com.qx.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { // 设置允许跨域的路径 registry.addMapping("/**") // 设置允许跨域请求的域名 .allowedOriginPatterns("*") // 是否允许cookie .allowCredentials(true) // 设置允许的请求方式 .allowedMethods("GET", "POST", "DELETE", "PUT") // 设置允许的header属性 .allowedHeaders("*") // 跨域允许时间 .maxAge(3600); }}
在SecurityConfig中开启开启SpringSecurity的跨域访问
由于我们的资源都会收到SpringSecurity的保护,所以想要跨域访问还要让SpringSecurity运行跨域访问。
package com.qx.config;import com.qx.filter.JwtAuthenticationTokenFilter;import com.qx.handler.AccessDeniedHandlerImpl;import com.qx.handler.AuthenticationEntryPointImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.security.web.access.AccessDeniedHandler;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import sun.security.util.Password;/** * @author : k * @Date : 2022/3/23 * @Desc : */@Configuration@EnableGlobalMethodSecurity(prePostEnabled =true) //开启授权注解功能public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; @Autowired private AuthenticationEntryPoint authenticationEntryPoint; @Autowired private AccessDeniedHandler accessDeniedHandler; //放行 @Override protected void configure(HttpSecurity http) throws Exception { http //关闭csrf .csrf().disable() //不通过Session获取SecurityContext .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() // 对于登录接口 允许匿名访问 .antMatchers("/user/login").anonymous() .antMatchers("/testCors").hasAuthority("system:dept:list211") // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated(); //将jwtAuthenticationTokenFilter过滤器放到登录认证之前 http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class); //配置异常处理器 http.exceptionHandling() //认证失败处理器 .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler); //允许跨域 http.cors(); } @Bean //这样子就可以从容器当中获取到AuthenticationManager @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); }}
8、自定义权限校验方法
我们也可以定义自己的权限校验方法,在@PreAuthorize注解中使用我们的方法。
package com.qx.expression;import com.qx.entity.LoginUser;import org.springframework.security.core.Authentication;import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.stereotype.Component;import java.util.List;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Component("ex")public class QXExpressionRoot { //String authority 这里是后端赋给它的权限 //从数据库获取登录用户的权限功能 和authority 进行对比 public boolean hasAuthority(String authority){ //获取当前用户得权限 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); List<String> permissions = loginUser.getPermissions(); //判断用户权限集合中是否存在 authority return permissions.contains(authority); }}
在SPEL表达式中使用 @ex相当于获取容器中bean的名字为ex的对象。然后再调用这个对象的hasAuthority方法
@RequestMapping("hello") //自定义的权限功能 @PreAuthorize("@ex.hasAuthority('system:dept:list')") public String hello(){ return "hello"; }
基于配置的权限控制
package com.qx.config;import com.qx.filter.JwtAuthenticationTokenFilter;import com.qx.handler.AccessDeniedHandlerImpl;import com.qx.handler.AuthenticationEntryPointImpl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.config.http.SessionCreationPolicy;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.AuthenticationEntryPoint;import org.springframework.security.web.access.AccessDeniedHandler;import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;import sun.security.util.Password;/** * @author : k * @Date : 2022/3/23 * @Desc : */@Configuration@EnableGlobalMethodSecurity(prePostEnabled =true) //开启授权注解功能public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Autowired private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; @Autowired private AuthenticationEntryPoint authenticationEntryPoint; @Autowired private AccessDeniedHandler accessDeniedHandler; //放行 @Override protected void configure(HttpSecurity http) throws Exception { http //关闭csrf .csrf().disable() //不通过Session获取SecurityContext .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() // 对于登录接口 允许匿名访问 .antMatchers("/user/login").anonymous() .antMatchers("/testCors").hasAuthority("system:dept:list211") // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated(); //将jwtAuthenticationTokenFilter过滤器放到登录认证之前 http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class); //配置异常处理器 http.exceptionHandling() //认证失败处理器 .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler); //允许跨域 http.cors(); } @Bean //这样子就可以从容器当中获取到AuthenticationManager @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); }}
9、CSRF
CSRF是指跨站请求伪造(Cross-site request forgery),是web常见的攻击之一。
https://blog.csdn.net/freeking101/article/details/86537087
SpringSecurity防止CSRF攻击的方式就是通过csrf_token。后端会生成一个csrf_token,前端发起请求的时候需要携带这个csrf_token,后端会有过滤器进行校验,如果没有携带或者是伪造的就不允许访问。
我们可以发现CSRF攻击依靠的是cookie中所携带的认证信息。但是在前后端分离的项目中我们的认证信息其实是token,而token并不是存储中cookie中,并且需要前端代码去把token设置到请求头中才可以,所以CSRF攻击也就不用担心了。
10、认证处理器
10.1、认证成功处理器
实际上在UsernamePasswordAuthenticationFilter进行登录认证的时候,如果登录成功了是会调用AuthenticationSuccessHandler的方法进行认证成功后的处理的。AuthenticationSuccessHandler就是登录成功处理器。
我们也可以自己去自定义成功处理器进行成功后的相应处理。
我们可以在入门案例中测试:
QXSuccessHandler
package com.qx.handler;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;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Componentpublic class QXSuccessHandler implements AuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { System.out.println("认证成功"); }}
SecurityConfig
package com.qx.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationSuccessHandler authencationSuccessHandler; @Autowired private AuthenticationFailureHandler authencationFailureHandler; @Autowired private LogoutSuccessHandler logoutSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(). //配置认证成功处理器 successHandler(authencationSuccessHandler) //配置认证失败处理器 .failureHandler(authencationFailureHandler); //配置注销成功处理器 http.logout().logoutSuccessHandler(logoutSuccessHandler); //因为重写了 所以需要手动添加认证规则 http.authorizeRequests().anyRequest().authenticated(); }}
10.2、认证失败处理器
QXFailureHandler
package com.qx.handler;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.AuthenticationFailureHandler;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;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Componentpublic class QXFailureHandler implements AuthenticationFailureHandler{ @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { System.out.println("认证失败"); }}
SecurityConfig
package com.qx.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationSuccessHandler authencationSuccessHandler; @Autowired private AuthenticationFailureHandler authencationFailureHandler; @Autowired private LogoutSuccessHandler logoutSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(). //配置认证成功处理器 successHandler(authencationSuccessHandler) //配置认证失败处理器 .failureHandler(authencationFailureHandler); //配置注销成功处理器 http.logout().logoutSuccessHandler(logoutSuccessHandler); //因为重写了 所以需要手动添加认证规则 http.authorizeRequests().anyRequest().authenticated(); }}
10.3、注销成功处理器
QXLogoutSuccessHandler
package com.qx.handler;import org.springframework.security.core.Authentication;import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import org.springframework.stereotype.Component;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Componentpublic class QXLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { System.out.println("注销成功"); }}
SecurityConfig
package com.qx.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;/** * @author : k * @Date : 2022/3/24 * @Desc : */@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private AuthenticationSuccessHandler authencationSuccessHandler; @Autowired private AuthenticationFailureHandler authencationFailureHandler; @Autowired private LogoutSuccessHandler logoutSuccessHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin(). //配置认证成功处理器 successHandler(authencationSuccessHandler) //配置认证失败处理器 .failureHandler(authencationFailureHandler); //配置注销成功处理器 http.logout().logoutSuccessHandler(logoutSuccessHandler); //因为重写了 所以需要手动添加认证规则 http.authorizeRequests().anyRequest().authenticated(); }}
彩蛋:
1、SecurityContextHolder:用于存储安全上下文SecurityContext信息,而这个SecurityContexr进一步持有Authentication 即代表的是当前的用户的所有信息:该用户是谁,是否已经被认证,拥有哪些角色…这些信息都被保存在Anthentication中。
SecurityContextHolder默认使用ThreadLocal 策略来存储认证信息,也就是说这是一种线程绑定信息的策略,Spring Security在用户登录时自动绑定认证信息到当前的线程,在用户退出时,自动清楚当前线程的认证信息。
2、Authentication
package org.springframework.security.core;import java.io.Serializable;import java.security.Principal;import java.util.Collection;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.core.context.SecurityContextHolder;public interface Authentication extends Principal, Serializable { //权限 集合中放的 是GrantedAuthority的子类 SimpleGrantedAuthority Collection<" />
也就是说GrantedAuthority里边存放的就是Authority 权限对象
4、UserDetails
package org.springframework.security.core.userdetails;import java.io.Serializable;import java.util.Collection;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;public interface UserDetails extends Serializable { Collection<? extends GrantedAuthority> getAuthorities();//权限标识集合 String getPassword(); //密码 String getUsername(); //用户名 boolean isAccountNonExpired(); //是否未过期 boolean isAccountNonLocked(); //是否未锁定 boolean isCredentialsNonExpired(); //凭证是否未过期 boolean isEnabled(); //是否可用}
5、UserDetailsService
public interface UserDetailsService { //通过username 查询 UserDetails UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;}
6、AuthenticationManager 认证管理器
public interface AuthenticationManager { //authenticate鉴定 对传入的authentication进行认证 Authentication authenticate(Authentication authentication) throws AuthenticationException;}
7、ProviderManager 是AuthenticationManager的实现类
package org.springframework.security.authentication;import java.util.Arrays;import java.util.Collections;import java.util.List;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.beans.factory.InitializingBean;import org.springframework.context.MessageSource;import org.springframework.context.MessageSourceAware;import org.springframework.context.support.MessageSourceAccessor;import org.springframework.core.log.LogMessage;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.CredentialsContainer;import org.springframework.security.core.SpringSecurityMessageSource;import org.springframework.util.Assert;import org.springframework.util.CollectionUtils;public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean { private static final Log logger = LogFactory.getLog(ProviderManager.class); private AuthenticationEventPublisher eventPublisher = new NullEventPublisher(); private List<AuthenticationProvider> providers = Collections.emptyList(); protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private AuthenticationManager parent; private boolean eraseCredentialsAfterAuthentication = true; public ProviderManager(AuthenticationProvider... providers) { this(Arrays.asList(providers), null); } public ProviderManager(List<AuthenticationProvider> providers) { this(providers, null); } public ProviderManager(List<AuthenticationProvider> providers, AuthenticationManager parent) { Assert.notNull(providers, "providers list cannot be null"); this.providers = providers; this.parent = parent; checkState(); } @Override public void afterPropertiesSet() { checkState(); } private void checkState() { Assert.isTrue(this.parent != null || !this.providers.isEmpty(), "A parent AuthenticationManager or a list of AuthenticationProviders is required"); Assert.isTrue(!CollectionUtils.contains(this.providers.iterator(), null), "providers list cannot contain null values"); } //实现了AuthenticationManager接口的方法 重点 @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; AuthenticationException parentException = null; Authentication result = null; Authentication parentResult = null; int currentPosition = 0; int size = this.providers.size(); for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Authenticating request with %s (%d/%d)", provider.getClass().getSimpleName(), ++currentPosition, size)); } try { result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); break; } } catch (AccountStatusException | InternalAuthenticationServiceException ex) { prepareException(ex, authentication); // SEC-546: Avoid polling additional providers if auth failure is due to // invalid account status throw ex; } catch (AuthenticationException ex) { lastException = ex; } } if (result == null && this.parent != null) { // Allow the parent to try. try { parentResult = this.parent.authenticate(authentication); result = parentResult; } catch (ProviderNotFoundException ex) { // ignore as we will throw below if no other exception occurred prior to // calling parent and the parent // may throw ProviderNotFound even though a provider in the child already // handled the request } catch (AuthenticationException ex) { parentException = ex; lastException = ex; } } if (result != null) { if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) { // Authentication is complete. Remove credentials and other secret data // from authentication ((CredentialsContainer) result).eraseCredentials(); } // If the parent AuthenticationManager was attempted and successful then it // will publish an AuthenticationSuccessEvent // This check prevents a duplicate AuthenticationSuccessEvent if the parent // AuthenticationManager already published it if (parentResult == null) { this.eventPublisher.publishAuthenticationSuccess(result); } return result; } // Parent was null, or didn't authenticate (or throw an exception). if (lastException == null) { lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } // If the parent AuthenticationManager was attempted and failed then it will // publish an AbstractAuthenticationFailureEvent // This check prevents a duplicate AbstractAuthenticationFailureEvent if the // parent AuthenticationManager already published it if (parentException == null) { prepareException(lastException, authentication); } throw lastException; } @SuppressWarnings("deprecation") private void prepareException(AuthenticationException ex, Authentication auth) { this.eventPublisher.publishAuthenticationFailure(ex, auth); } private void copyDetails(Authentication source, Authentication dest) { if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) { AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest; token.setDetails(source.getDetails()); } } public List<AuthenticationProvider> getProviders() { return this.providers; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null"); this.eventPublisher = eventPublisher; } public void setEraseCredentialsAfterAuthentication(boolean eraseSecretData) { this.eraseCredentialsAfterAuthentication = eraseSecretData; } public boolean isEraseCredentialsAfterAuthentication() { return this.eraseCredentialsAfterAuthentication; } private static final class NullEventPublisher implements AuthenticationEventPublisher { @Override public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) { } @Override public void publishAuthenticationSuccess(Authentication authentication) { } }}
8、AuthenticationProvider
package org.springframework.security.authentication;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;public interface AuthenticationProvider { //认证 Authentication Authentication authenticate(Authentication authentication) throws AuthenticationException;//是否支持传入authentication boolean supports(Class<?> authentication);} } } if (result != null) { if (this.eraseCredentialsAfterAuthentication && (result instanceof CredentialsContainer)) { // Authentication is complete. Remove credentials and other secret data // from authentication ((CredentialsContainer) result).eraseCredentials(); } // If the parent AuthenticationManager was attempted and successful then it // will publish an AuthenticationSuccessEvent // This check prevents a duplicate AuthenticationSuccessEvent if the parent // AuthenticationManager already published it if (parentResult == null) { this.eventPublisher.publishAuthenticationSuccess(result); } return result; } // Parent was null, or didn't authenticate (or throw an exception). if (lastException == null) { lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[] { toTest.getName() }, "No AuthenticationProvider found for {0}")); } // If the parent AuthenticationManager was attempted and failed then it will // publish an AbstractAuthenticationFailureEvent // This check prevents a duplicate AbstractAuthenticationFailureEvent if the // parent AuthenticationManager already published it if (parentException == null) { prepareException(lastException, authentication); } throw lastException; } @SuppressWarnings("deprecation") private void prepareException(AuthenticationException ex, Authentication auth) { this.eventPublisher.publishAuthenticationFailure(ex, auth); } private void copyDetails(Authentication source, Authentication dest) { if ((dest instanceof AbstractAuthenticationToken) && (dest.getDetails() == null)) { AbstractAuthenticationToken token = (AbstractAuthenticationToken) dest; token.setDetails(source.getDetails()); } } public List<AuthenticationProvider> getProviders() { return this.providers; } @Override public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } public void setAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher) { Assert.notNull(eventPublisher, "AuthenticationEventPublisher cannot be null"); this.eventPublisher = eventPublisher; } public void setEraseCredentialsAfterAuthentication(boolean eraseSecretData) { this.eraseCredentialsAfterAuthentication = eraseSecretData; } public boolean isEraseCredentialsAfterAuthentication() { return this.eraseCredentialsAfterAuthentication; } private static final class NullEventPublisher implements AuthenticationEventPublisher { @Override public void publishAuthenticationFailure(AuthenticationException exception, Authentication authentication) { } @Override public void publishAuthenticationSuccess(Authentication authentication) { } }}
8、AuthenticationProvider
package org.springframework.security.authentication;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;public interface AuthenticationProvider { //认证 Authentication Authentication authenticate(Authentication authentication) throws AuthenticationException;//是否支持传入authentication boolean supports(Class<?> authentication);}