0


SpringSecurity框架【详解】

SpringSecurity

来源视频

文章目录

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是一个强大而灵活的开源安全框架,能够非常清晰的处理认证、授权、管理会话以及密码加密。如下是它所具有的特点:

  1. 易于理解的 Java Security API;
  2. 简单的身份认证(登录),支持多种数据源(LDAP,JDBC,Kerberos,ActiveDirectory 等);
  3. 对角色的简单的签权(访问控制),支持细粒度的签权;
  4. 支持一级缓存,以提升应用程序的性能;
  5. 内置的基于 POJO 企业会话管理,适用于 Web 以及非 Web 的环境;
  6. 异构客户端会话访问;
  7. 非常简单的加密 API;
  8. 不跟任何的框架或者容器捆绑,可以独立运行。Shiro四大核心功能:Authentication,Authorization,Cryptography,Session Management

img

四大核心功能介绍:
  1. Authentication:身份认证/登录,验证用户是不是拥有相应的身份;
  2. Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
  3. Session Manager:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的;
  4. Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
Shiro架构
Shiro三个核心组件:Subject, SecurityManager 和 Realms.
  1. Subject:主体,可以看到主体可以是任何可以与应用交互的 用户;
  2. SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。
  3. 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一般流程为:

  1. 当用户登录时,前端将用户输入的用户名、密码信息传输到后台,后台用一个类对象将其封装起来,通常使用的是UsernamePasswordAuthenticationToken这个类。
  2. 程序负责验证这个类对象。验证方法是调用Service根据username从数据库中取用户信息到实体类的实例中,比较两者的密码,如果密码正确就成功登陆,同时把包含着用户的用户名、密码、所具有的权限等信息的类对象放到SecurityContextHolder(安全上下文容器,类似Session)中去。
  3. 用户访问一个资源的时候,首先判断是否是受限资源。如果是的话还要判断当前是否未登录,没有的话就跳到登录页面。
  4. 如果用户已经登录,访问一个受限资源的时候,程序要根据url去数据库中取出该资源所对应的所有可以访问的角色,然后拿着当前用户的所有角色一一对比,判断用户是否可以访问(这里就是和权限相关)。

2.2.1、spring-security的优点

  • spring-security对spring整合较好,使用起来更加方便;
  • 有更强大的spring社区进行支持;
  • 支持第三方的 oauth 授权,官方网站:spring-security-oauth

3、快速入门

3.1、装备工作

​ 我们先创建一个空项目

image-20220326153556239

在项目中创建一个普通的maven项目

image-20220326153933673

在这里插入图片描述

image-20220326154028071

将该普通的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、创建启动类

@SpringBootApplicationpublicclassIntroductionSpringSecurity{publicstaticvoidmain(String[] args){SpringApplication.run(IntroductionSpringSecurity.class,args);}}

3、创建Controller

@RestControllerpublicclassHelloController{@RequestMapping("/hello")publicStringhello(){return"World Hello";}}

测试访问:

image-20220326154922271

4、导入SpringSecurity依赖

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

重新启动测试:

这时我们可以看到当我们访问我们的接口的时候,就会自动跳转到一个SpringSecurity的默认登陆页面
image-20220326155136806

image-20220326155304924

这时候需要我们登录才可以进行访问

,我们可以看到控制台有一串字符串,其实那就是SpringSecurity初始化生成给我的密码

默认用户名:user

输入用户名和密码,再次登录

image-20220326155357383

成功。

4、认证

4.1、登录流程校验

在这里插入图片描述

4.2、入门案例的原理

前后端认证流程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LKooVd3p-1648311184478)(C:\Users\30666\AppData\Roaming\Typora\typora-user-images\image-20220326160405082.png?lastModify=1648282919)]

  1. UsernamePasswordAuthenticationFilter:是我们最常用的用户名和密码认证方式的主要处理类,构造了一个UsernamePasswordAuthenticationToken对象实现类,将用请求信息封装为Authentication
  2. Authentication接口: 封装了用户相关信息。
  3. AuthenticationManager接口:定义了认证Authentication的方法,是认证相关的核心接口,也是发起认证的出发点,因为在实际需求中,我们可能会允许用户使用用户名+密码登录,同时允许用户使用邮箱+密码,手机号码+密码登录,甚至,可能允许用户使用指纹登录(还有这样的操作?没想到吧),所以说AuthenticationManager一般不直接认证AuthenticationManager接口的常用实现类ProviderManager 内部会维护一个List列表,存放多种认证方式,实际上这是委托者模式的应用(Delegate)。也就是说,核心的认证入口始终只有一个:AuthenticationManagerAuthenticationManager,ProviderManager ,AuthenticationProvider…用户名+密码(UsernamePasswordAuthenticationToken),邮箱+密码,手机号码+密码登录则对应了三个AuthenticationProvider
  4. DaoAuthenticationProvider:用于解析并认证 UsernamePasswordAuthenticationToken 的这样一个认证服务提供者,对应以上的几种登录方式。
  5. UserDetailsService接口:Spring Security 会将前端填写的username 传给 UserDetailService.loadByUserName方法。我们只需要从数据库中根据用户名查找到用户信息然后封装为UserDetails的实现类返回给SpringSecurity 即可,自己不需要进行密码的比对工作,密码比对交由SpringSecurity处理。
  6. UserDetails接口:提供核心用户信息。通过UserDetailsService根据用户名获取处理的用户信息要封装成UserDetails对象返回。然后将这些信息封装到Authentication对象中。

图片描述

UsernamePasswordAuthenticationFilter:

是我们最常用的用户名和密码认证方式的主要处理类,构造了一个UsernamePasswordAuthenticationToken对象实现类,将用请求信息封装为Authentication

BasicAuthenticationFilter...:

将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><!--        redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--        json--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency><!--        jwt--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency><!--        mysql--><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><!--       mybatis-plus-boot-starter--><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
packagecom.qx.utils;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.serializer.SerializerFeature;importcom.fasterxml.jackson.databind.JavaType;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.databind.type.TypeFactory;importorg.springframework.data.redis.serializer.RedisSerializer;importorg.springframework.data.redis.serializer.SerializationException;importcom.alibaba.fastjson.parser.ParserConfig;importorg.springframework.util.Assert;importjava.nio.charset.Charset;/**
 * Redis使用FastJson序列化
 */publicclassFastJsonRedisSerializer<T>implementsRedisSerializer<T>{publicstaticfinalCharset DEFAULT_CHARSET =Charset.forName("UTF-8");privateClass<T> clazz;static{ParserConfig.getGlobalInstance().setAutoTypeSupport(true);}publicFastJsonRedisSerializer(Class<T> clazz){super();this.clazz = clazz;}@Overridepublicbyte[]serialize(T t)throwsSerializationException{if(t ==null){returnnewbyte[0];}return JSON.toJSONString(t,SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@OverridepublicTdeserialize(byte[] bytes)throwsSerializationException{if(bytes ==null|| bytes.length <=0){returnnull;}String str =newString(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}protectedJavaTypegetJavaType(Class<?> clazz){returnTypeFactory.defaultInstance().constructType(clazz);}}

3.在主启动类同级目录下建立config包

RedisConfig
packagecom.qx.config;importcom.qx.utils.FastJsonRedisSerializer;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.redis.connection.RedisConnectionFactory;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.serializer.StringRedisSerializer;@ConfigurationpublicclassRedisConfig{@Bean@SuppressWarnings(value ={"unchecked","rawtypes"})publicRedisTemplate<Object,Object>redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<Object,Object> template =newRedisTemplate<>();
        template.setConnectionFactory(connectionFactory);FastJsonRedisSerializer serializer =newFastJsonRedisSerializer(Object.class);// 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(newStringRedisSerializer());
        template.setValueSerializer(serializer);// Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(newStringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();return template;}}

4.在主启动类同级目录下建立controller包

响应类ResponseResult
packagecom.qx.domain;importcom.fasterxml.jackson.annotation.JsonInclude;@JsonInclude(JsonInclude.Include.NON_NULL)publicclassResponseResult<T>{/**
     * 状态码
     */privateInteger code;/**
     * 提示信息,如果有错误时,前端可以获取该字段进行提示
     */privateString msg;/**
     * 查询到的结果数据,
     */privateT data;publicResponseResult(Integer code,String msg){this.code = code;this.msg = msg;}publicResponseResult(Integer code,T data){this.code = code;this.data = data;}publicIntegergetCode(){return code;}publicvoidsetCode(Integer code){this.code = code;}publicStringgetMsg(){return msg;}publicvoidsetMsg(String msg){this.msg = msg;}publicTgetData(){return data;}publicvoidsetData(T data){this.data = data;}publicResponseResult(Integer code,String msg,T data){this.code = code;this.msg = msg;this.data = data;}}

5.将工具类置于utils包

JwtUtil
packagecom.qx.utils;importio.jsonwebtoken.Claims;importio.jsonwebtoken.JwtBuilder;importio.jsonwebtoken.Jwts;importio.jsonwebtoken.SignatureAlgorithm;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjava.util.Base64;importjava.util.Date;importjava.util.UUID;/**
 * JWT工具类
 */publicclassJwtUtil{//有效期为publicstaticfinalLong JWT_TTL =60*60*1000L;// 60 * 60 *1000  一个小时//设置秘钥明文publicstaticfinalString JWT_KEY ="qx";publicstaticStringgetUUID(){String token = UUID.randomUUID().toString().replaceAll("-","");return token;}/**
     * 生成jtw  jwt加密
     * @param subject token中要存放的数据(json格式)
     * @return
     */publicstaticStringcreateJWT(String subject){JwtBuilder builder =getJwtBuilder(subject,null,getUUID());// 设置过期时间return builder.compact();}/**
     * 生成jtw  jwt加密
     * @param subject token中要存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return
     */publicstaticStringcreateJWT(String subject,Long ttlMillis){JwtBuilder builder =getJwtBuilder(subject, ttlMillis,getUUID());// 设置过期时间return builder.compact();}/**
     * 创建token jwt加密
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */publicstaticStringcreateJWT(String id,String subject,Long ttlMillis){JwtBuilder builder =getJwtBuilder(subject, ttlMillis, id);// 设置过期时间return builder.compact();}privatestaticJwtBuildergetJwtBuilder(String subject,Long ttlMillis,String uuid){SignatureAlgorithm signatureAlgorithm =SignatureAlgorithm.HS256;SecretKey secretKey =generalKey();long nowMillis =System.currentTimeMillis();Date now =newDate(nowMillis);if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;}long expMillis = nowMillis + ttlMillis;Date expDate =newDate(expMillis);returnJwts.builder().setId(uuid)//唯一的ID.setSubject(subject)// 主题  可以是JSON数据.setIssuer("sg")// 签发者.setIssuedAt(now)// 签发时间.signWith(signatureAlgorithm, secretKey)//使用HS256对称加密算法签名, 第二个参数为秘钥.setExpiration(expDate);}publicstaticvoidmain(String[] args)throwsException{//jwt加密String jwt =createJWT("123456");//jwt解密Claims claims =parseJWT(jwt);String subject = claims.getSubject();System.out.println(subject);System.out.println(jwt);}/**
     * 生成加密后的秘钥 secretKey
     * @return
     */publicstaticSecretKeygeneralKey(){byte[] encodedKey =Base64.getDecoder().decode(JwtUtil.JWT_KEY);SecretKey key =newSecretKeySpec(encodedKey,0, encodedKey.length,"AES");return key;}/**
     * jwt解密
     *
     * @param jwt
     * @return
     * @throws Exception
     */publicstaticClaimsparseJWT(String jwt)throwsException{SecretKey secretKey =generalKey();returnJwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();}}
RedisCache
packagecom.qx.utils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.redis.core.BoundSetOperations;importorg.springframework.data.redis.core.HashOperations;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.stereotype.Component;importjava.util.*;importjava.util.concurrent.TimeUnit;@SuppressWarnings(value ={"unchecked","rawtypes"})@ComponentpublicclassRedisCache{@AutowiredpublicRedisTemplate redisTemplate;/**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */public<T>voidsetCacheObject(finalString key,finalT value){
        redisTemplate.opsForValue().set(key, value);}/**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */public<T>voidsetCacheObject(finalString key,finalT value,finalInteger timeout,finalTimeUnit timeUnit){
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */publicbooleanexpire(finalString key,finallong timeout){returnexpire(key, timeout,TimeUnit.SECONDS);}/**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */publicbooleanexpire(finalString key,finallong timeout,finalTimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */public<T>TgetCacheObject(finalString key){ValueOperations<String,T> operation = redisTemplate.opsForValue();return operation.get(key);}/**
     * 删除单个对象
     *
     * @param key
     */publicbooleandeleteObject(finalString key){return redisTemplate.delete(key);}/**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */publiclongdeleteObject(finalCollection collection){return redisTemplate.delete(collection);}/**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */public<T>longsetCacheList(finalString key,finalList<T> dataList){Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count ==null?0: count;}/**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */public<T>List<T>getCacheList(finalString key){return redisTemplate.opsForList().range(key,0,-1);}/**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */public<T>BoundSetOperations<String,T>setCacheSet(finalString key,finalSet<T> dataSet){BoundSetOperations<String,T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while(it.hasNext()){
            setOperation.add(it.next());}return setOperation;}/**
     * 获得缓存的set
     *
     * @param key
     * @return
     */public<T>Set<T>getCacheSet(finalString key){return redisTemplate.opsForSet().members(key);}/**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */public<T>voidsetCacheMap(finalString key,finalMap<String,T> dataMap){if(dataMap !=null){
            redisTemplate.opsForHash().putAll(key, dataMap);}}/**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */public<T>Map<String,T>getCacheMap(finalString key){return redisTemplate.opsForHash().entries(key);}/**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */public<T>voidsetCacheMapValue(finalString key,finalString hKey,finalT value){
        redisTemplate.opsForHash().put(key, hKey, value);}/**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */public<T>TgetCacheMapValue(finalString key,finalString hKey){HashOperations<String,String,T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/**
     * 删除Hash中的数据
     * 
     * @param key
     * @param hkey
     */publicvoiddelCacheMapValue(finalString key,finalString hkey){HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);}/**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */public<T>List<T>getMultiCacheMapValue(finalString key,finalCollection<Object> hKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);}/**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */publicCollection<String>keys(finalString pattern){return redisTemplate.keys(pattern);}}
WebUtils
packagecom.qx.utils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.data.redis.core.BoundSetOperations;importorg.springframework.data.redis.core.HashOperations;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.data.redis.core.ValueOperations;importorg.springframework.stereotype.Component;importjava.util.*;importjava.util.concurrent.TimeUnit;@SuppressWarnings(value ={"unchecked","rawtypes"})@ComponentpublicclassRedisCache{@AutowiredpublicRedisTemplate redisTemplate;/**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */public<T>voidsetCacheObject(finalString key,finalT value){
        redisTemplate.opsForValue().set(key, value);}/**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */public<T>voidsetCacheObject(finalString key,finalT value,finalInteger timeout,finalTimeUnit timeUnit){
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */publicbooleanexpire(finalString key,finallong timeout){returnexpire(key, timeout,TimeUnit.SECONDS);}/**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */publicbooleanexpire(finalString key,finallong timeout,finalTimeUnit unit){return redisTemplate.expire(key, timeout, unit);}/**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */public<T>TgetCacheObject(finalString key){ValueOperations<String,T> operation = redisTemplate.opsForValue();return operation.get(key);}/**
     * 删除单个对象
     *
     * @param key
     */publicbooleandeleteObject(finalString key){return redisTemplate.delete(key);}/**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */publiclongdeleteObject(finalCollection collection){return redisTemplate.delete(collection);}/**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */public<T>longsetCacheList(finalString key,finalList<T> dataList){Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count ==null?0: count;}/**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */public<T>List<T>getCacheList(finalString key){return redisTemplate.opsForList().range(key,0,-1);}/**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */public<T>BoundSetOperations<String,T>setCacheSet(finalString key,finalSet<T> dataSet){BoundSetOperations<String,T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while(it.hasNext()){
            setOperation.add(it.next());}return setOperation;}/**
     * 获得缓存的set
     *
     * @param key
     * @return
     */public<T>Set<T>getCacheSet(finalString key){return redisTemplate.opsForSet().members(key);}/**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */public<T>voidsetCacheMap(finalString key,finalMap<String,T> dataMap){if(dataMap !=null){
            redisTemplate.opsForHash().putAll(key, dataMap);}}/**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */public<T>Map<String,T>getCacheMap(finalString key){return redisTemplate.opsForHash().entries(key);}/**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */public<T>voidsetCacheMapValue(finalString key,finalString hKey,finalT value){
        redisTemplate.opsForHash().put(key, hKey, value);}/**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */public<T>TgetCacheMapValue(finalString key,finalString hKey){HashOperations<String,String,T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/**
     * 删除Hash中的数据
     * 
     * @param key
     * @param hkey
     */publicvoiddelCacheMapValue(finalString key,finalString hkey){HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);}/**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */public<T>List<T>getMultiCacheMapValue(finalString key,finalCollection<Object> hKeys){return redisTemplate.opsForHash().multiGet(key, hKeys);}/**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */publicCollection<String>keys(finalString pattern){return redisTemplate.keys(pattern);}}

6.建立实体类

packagecom.qx.entity;importcom.baomidou.mybatisplus.annotation.TableId;importcom.baomidou.mybatisplus.annotation.TableName;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importjava.io.Serializable;importjava.util.Date;/**
 * 用户表(User)实体类
 *
 *
 */@Data@AllArgsConstructor@NoArgsConstructor@TableName("sys_user")publicclassUserimplementsSerializable{privatestaticfinallong serialVersionUID =-40356785423868312L;/**
    * 主键
    */@TableIdprivateLong id;/**
    * 用户名
    */privateString userName;/**
    * 昵称
    */privateString nickName;/**
    * 密码
    */privateString password;/**
    * 账号状态(0正常 1停用)
    */privateString status;/**
    * 邮箱
    */privateString email;/**
    * 手机号
    */privateString phonenumber;/**
    * 用户性别(0男,1女,2未知)
    */privateString sex;/**
    * 头像
    */privateString avatar;/**
    * 用户类型(0管理员,1普通用户)
    */privateString userType;/**
    * 创建人的用户id
    */privateLong createBy;/**
    * 创建时间
    */privateDate createTime;/**
    * 更新人
    */privateLong updateBy;/**
    * 更新时间
    */privateDate updateTime;/**
    * 删除标志(0代表未删除,1代表已删除)
    */privateInteger delFlag;}

4.3.2、实现

从之前的分析我们可以知道,我们可以自定义一个UserDetailsService,让SpringSecurity使用我们的UserDetailsService。我们自己的UserDetailsService可以从数据库中查询用户名和密码。

准备工作

​ 创建一个用户表, 建表语句如下

CREATETABLE`sys_user`(`id`bigintNOTNULLAUTO_INCREMENTCOMMENT'主键',`user_name`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'用户名',`nick_name`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'呢称',`password`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'密码',`status`char(1)DEFAULT'0'COMMENT'账号状态(0正常1停用)',`email`varchar(64)DEFAULTNULLCOMMENT'邮箱',`phonenumber`varchar(32)DEFAULTNULLCOMMENT'手机号',`sex`char(1)DEFAULTNULLCOMMENT'用户性别(0男,1女,2未知)',`avatar`varchar(128)DEFAULTNULLCOMMENT'头像',`user_type`char(1)NOTNULLDEFAULT'1'COMMENT'用户类型(O管理员,1普通用户)',`create_by`bigintDEFAULTNULLCOMMENT'创建人的用户id',`create_time`datetimeDEFAULTNULLCOMMENT'创建时间',`update_by`bigintDEFAULTNULLCOMMENT'更新人',`update_time`datetimeDEFAULTNULLCOMMENT'更新时间',`del_flag`intDEFAULT'0'COMMENT'删除标志(O代表未删除,1代表已删除)',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户表';

配置数据库信息

spring:datasource:url: jdbc:mysql://localhost:3306/qx_security?characterEncoding=utf-8&serverTimezone=UTCusername: root
    password:123456driver-class-name: com.mysql.cj.jdbc.Driver
server:port:8888

定义Mapper接口

@Mapper@RepositorypublicinterfaceUserMapperextendsBaseMapper<User>{}

测试MP是否能正常使用

/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@SpringBootTestpublicclassUserMapperTests{@AutowiredprivateUserMapper userMapper;@TestpublicvoidtestUserMapper(){List<User> userList = userMapper.selectList(null);for(User user : userList){System.out.println(user);}}}

4.3.3、核心代码实现

创建一个类实现UserDetailsService接口,重写其中的方法。增加用户名从数据库中查询用户信息

packagecom.qx.service.impl;importcom.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;importcom.qx.entity.LoginUser;importcom.qx.entity.User;importcom.qx.mapper.MenuMapper;importcom.qx.mapper.UserMapper;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.stereotype.Service;importjava.util.List;importjava.util.Objects;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@ServicepublicclassUserDetailsServiceImplimplementsUserDetailsService{@AutowiredprivateUserMapper userMapper;//实现UserDetailsService接口,重写UserDetails方法,自定义用户的信息从数据中查询@OverridepublicUserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException{//(认证,即校验该用户是否存在)查询用户信息LambdaQueryWrapper<User> queryWrapper =newLambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);User user = userMapper.selectOne(queryWrapper);//如果没有查询到用户if(Objects.isNull(user)){thrownewRuntimeException("用户名或者密码错误");}//TODO (授权,即查询用户具有哪些权限)查询对应的用户信息//把数据封装成UserDetails返回returnnewLoginUser(user);}}
因为UserDetailsService方法的返回值是UserDetails类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。
@Data@NoArgsConstructor@AllArgsConstructorpublicclassLoginUserimplementsUserDetails{privateUser user;@OverridepublicCollection<?extendsGrantedAuthority>getAuthorities(){returnnull;}@OverridepublicStringgetPassword(){return user.getPassword();}@OverridepublicStringgetUsername(){return user.getUserName();}//是否未过期@OverridepublicbooleanisAccountNonExpired(){returntrue;}//是否未锁定@OverridepublicbooleanisAccountNonLocked(){returntrue;}//凭证是否未过期@OverridepublicbooleanisCredentialsNonExpired(){returntrue;}//是否可用@OverridepublicbooleanisEnabled(){returntrue;}}

注意:如果要测试,需要往用户表中写入用户数据,并且如果你想让用户的密码是明文存储,需要在密码前加{noop}。

4.3.3.1、密码加密存储
实际项目中我们不会把密码明文存储在数据库中。

​ 默认使用的PasswordEncoder要求数据库中的密码格式为:{id}password 。它会根据id去判断密码的加密方式。但是我们一般不会采用这种方式。所以就需要替换PasswordEncoder。

​ 我们一般使用SpringSecurity为我们提供的

BCryptPasswordEncoder。

​ 只需要使用把BCryptPasswordEncoder对象注入Spring容器中,SpringSecurity就会使用该PasswordEncoder来进行密码校验。

我们可以定义一个SpringSecurity的配置类,SpringSecurity要求这个配置类要继承WebSecurityConfigurerAdapter。

配置类置于config包下

@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}}
4.3.3.2、登陆接口

接下我们需要自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问。

​ 在接口中我们通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。

​ 认证成功的话要生成一个jwt,放入响应中返回。并且为了让用户下回请求时能通过jwt识别出具体的是哪个用户,我们需要把用户信息存入redis,可以把用户id作为key。

LoginController
packagecom.qx.controller;importcom.qx.entity.User;importcom.qx.service.LoginService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RestController;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@RestControllerpublicclassLoginController{@AutowiredprivateLoginService loginService;@PostMapping("/user/login")publicResponseResultlogin(@RequestBodyUser user){return loginService.login(user);}}
开发登录接口
通过AuthenticationManager的authenticate方法来进行用户认证,需要在SecurityConfig中配置把AuthenticationManager注入容器
SecurityConfig
/**
 * @Author 三更  B站: https://space.bilibili.com/663528522
 */@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http
                //关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();}@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}}
登录接口:LoginService
packagecom.qx.service;importcom.qx.controller.ResponseResult;importcom.qx.entity.User;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */publicinterfaceLoginService{ResponseResultlogin(User user);ResponseResultlogout();}
登录接口实现类:
通过AuthenticationManager的authenticate方法来进行用户认证,需要在SecurityConfig中配置把AuthenticationManager注入容器
认证实现

LoginServiceImpl

packagecom.qx.service.impl;importcom.qx.entity.LoginUser;importcom.qx.controller.ResponseResult;importcom.qx.entity.User;importcom.qx.service.LoginService;importcom.qx.utils.JwtUtil;importcom.qx.utils.RedisCache;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.authentication.UsernamePasswordAuthenticationToken;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.context.SecurityContextHolder;importorg.springframework.stereotype.Service;importjava.util.HashMap;importjava.util.Map;importjava.util.Objects;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@ServicepublicclassLoginServiceImplimplementsLoginService{@AutowiredprivateAuthenticationManager authenticationManager;@AutowiredprivateRedisCache redisCache;@OverridepublicResponseResultlogin(User user){//通过UsernamePasswordAuthenticationToken获取用户名和密码 UsernamePasswordAuthenticationToken authenticationToken=newUsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());//AuthenticationManager委托机制对authenticationToken 进行用户认证Authentication authenticate = authenticationManager.authenticate(authenticationToken);//如果认证没有通过,给出对应的提示if(Objects.isNull(authenticate)){thrownewRuntimeException("登录失败");}//如果认证通过,使用user生成jwt  jwt存入ResponseResult 返回//如果认证通过,拿到这个当前登录用户信息LoginUser loginUser =(LoginUser) authenticate.getPrincipal();//获取当前用户的useridString userid = loginUser.getUser().getId().toString();String jwt =JwtUtil.createJWT(userid);Map<String,String> map =newHashMap<>();
        map.put("token",jwt);//把完整的用户信息存入redis  userid为key   用户信息为value
        redisCache.setCacheObject("login:"+userid,loginUser);returnnewResponseResult(200,"登录成功",map);}}
4.3.3.3、认证过滤器

​ 我们需要自定义一个过滤器,这个过滤器会去获取请求头中的token,

对token进行解析取出其中的userid。
使用userid去redis中获取对应的LoginUser对象

。然后封装Authentication对象存入SecurityContextHolder

JwtAuthenticationTokenFilter
@ComponentpublicclassJwtAuthenticationTokenFilterextendsOncePerRequestFilter{@AutowiredprivateRedisCache redisCache;@OverrideprotectedvoiddoFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain)throwsServletException,IOException{//获取tokenString token = request.getHeader("token");if(!StringUtils.hasText(token)){//放行
            filterChain.doFilter(request, response);return;}//解析tokenString userid;try{Claims claims =JwtUtil.parseJWT(token);
            userid = claims.getSubject();}catch(Exception e){
            e.printStackTrace();thrownewRuntimeException("token非法");}//从redis中获取用户信息String redisKey ="login:"+ userid;LoginUser loginUser = redisCache.getCacheObject(redisKey);if(Objects.isNull(loginUser)){thrownewRuntimeException("用户未登录");}//封装Authentication对象存入SecurityContextHolder//TODO 获取权限信息封装到Authentication中UsernamePasswordAuthenticationToken authenticationToken =newUsernamePasswordAuthenticationToken(loginUser,null,null);SecurityContextHolder.getContext().setAuthentication(authenticationToken);//放行
        filterChain.doFilter(request, response);}}
SecurityConfig
//把token校验过滤器添加到过滤器链中
    http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@AutowiredJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http
                //关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();//把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);}@Bean@OverridepublicAuthenticationManagerauthenticationManagerBean()throwsException{returnsuper.authenticationManagerBean();}}
4.3.3.4、退出登陆

​ 我们只需要定义一个登陆接口,然后获取SecurityContextHolder中的认证信息,删除redis中对应的数据即可。

service层

LoginService
packagecom.qx.service;importcom.qx.controller.ResponseResult;importcom.qx.entity.User;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */publicinterfaceLoginService{ResponseResultlogin(User user);ResponseResultlogout();}

实现类

LoginServiceImpl
@OverridepublicResponseResultlogout(){//从SecurityContextHolder中的useridUsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser =(LoginUser) authentication.getPrincipal();Long userid = loginUser.getUser().getId();//根据userid找到redis对应值进行删除
        redisCache.deleteObject("login:"+userid);returnnewResponseResult(200,"注销成功");}
packagecom.qx.service.impl;importcom.qx.entity.LoginUser;importcom.qx.controller.ResponseResult;importcom.qx.entity.User;importcom.qx.service.LoginService;importcom.qx.utils.JwtUtil;importcom.qx.utils.RedisCache;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.authentication.UsernamePasswordAuthenticationToken;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.context.SecurityContextHolder;importorg.springframework.stereotype.Service;importjava.util.HashMap;importjava.util.Map;importjava.util.Objects;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@ServicepublicclassLoginServiceImplimplementsLoginService{@AutowiredprivateAuthenticationManager authenticationManager;@AutowiredprivateRedisCache redisCache;//进行认证@OverridepublicResponseResultlogin(User user){//通过UsernamePasswordAuthenticationToken获取用户名和密码UsernamePasswordAuthenticationToken authenticationToken=newUsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());//AuthenticationManager委托机制对authenticationToken 进行用户认证Authentication authenticate = authenticationManager.authenticate(authenticationToken);//如果认证没有通过,给出对应的提示if(Objects.isNull(authenticate)){thrownewRuntimeException("登录失败");}//如果认证通过,使用user生成jwt  jwt存入ResponseResult 返回//如果认证通过,拿到这个当前登录用户信息LoginUser loginUser =(LoginUser) authenticate.getPrincipal();//获取当前用户的useridString userid = loginUser.getUser().getId().toString();String jwt =JwtUtil.createJWT(userid);Map<String,String> map =newHashMap<>();
        map.put("token",jwt);//把完整的用户信息存入redis  userid为key 用户信息为value
        redisCache.setCacheObject("login:"+userid,loginUser);returnnewResponseResult(200,"登录成功",map);}@OverridepublicResponseResultlogout(){//从SecurityContextHolder中的useridUsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser =(LoginUser) authentication.getPrincipal();Long userid = loginUser.getUser().getId();//根据userid找到redis对应值进行删除
        redisCache.deleteObject("login:"+userid);returnnewResponseResult(200,"注销成功");}}

controller层

LoginController

@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
       return loginService.login(user);
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
       return loginService.logout();

    }

}

5、授权

5.1、权限的作用

​ 例如一个学校图书馆的管理系统,如果是普通学生登录就能看到借书还书相关的功能,不可能让他看到并且去使用添加书籍信息、删除书籍信息等功能。但是如果是一个图书馆管理员的账号登录了,应该就能看到并使用添加书籍信息,删除书籍信息等功能。

​ 总结起来就是

不同的用户可以使用不同的功能

。这就是权限系统要去实现的效果。

​ 我们不能只依赖前端去判断用户的权限来选择显示哪些菜单哪些按钮。因为如果只是这样,如果有人知道了对应功能的接口地址就可以不通过前端,直接去发送请求来实现相关功能操作。

​ 所以我们还需要在后台进行用户权限的判断,判断当前用户是否有相应的权限,必须具有所需权限才能进行相应的操作。

5.2、授权基本流程

​ 在SpringSecurity中,会使用默认的

FilterSecurityInterceptor来进行权限校验

。在FilterSecurityInterceptor中会

从SecurityContextHolder获取其中的Authentication

,然后获取其中的权限信息。当前用户是否拥有访问当前资源所需的权限。

​ 所以我们在项目中只需要把

当前登录用户的权限信息也存入Authentication

。然后设置我们的资源所需要的权限即可。

5.3、授权实现

5.3.1、限制访问资源所需权限

​ SpringSecurity为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式。我们可以使用注解去指定访问对应的资源所需的权限。

​ 但是要使用它我们需要先开启相关配置。

SecurityConfig

在类上增加以下字句,开启注解功能

@EnableGlobalMethodSecurity(prePostEnabled =true)//开启授权注解功能

就可以使用对应的注解。@PreAuthorize

/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@RestControllerpublicclassHelloController{@RequestMapping("/hello")@PreAuthorize("hasAuthority('test')")publicStringhello(){return"hello";}}

5.3.2、封装权限信息

​ 我们前面在写UserDetailsServiceImpl的时候说过,在查询出用户后还要获取对应的权限信息,封装到UserDetails中返回。进行了 //TODO标注

​ 我们先直接把权限信息写死封装到UserDetails中进行测试。

​ 我们之前定义了UserDetails的实现类LoginUser,想要让其能封装权限信息就要对其进行修改。

LoginUser
packagecom.qx.entity;importcom.alibaba.fastjson.annotation.JSONField;importlombok.Data;importlombok.NoArgsConstructor;importorg.springframework.security.core.GrantedAuthority;importorg.springframework.security.core.authority.SimpleGrantedAuthority;importorg.springframework.security.core.userdetails.UserDetails;importjava.util.Collection;importjava.util.List;importjava.util.stream.Collectors;@Data@NoArgsConstructorpublicclassLoginUserimplementsUserDetails{privateUser user;//存放当前登录用户的权限信息,一个用户可以有多个权限privateList<String> permissions;publicLoginUser(User user,List<String> permissions){this.user = user;this.permissions = permissions;}//权限集合@JSONField(serialize =false)privateList<SimpleGrantedAuthority>  authorities;//获取权限信息@OverridepublicCollection<?extendsGrantedAuthority>getAuthorities(){if(authorities!=null){return authorities;}//把permissions中String类型的权限信息封装成SimpleGrantedAuthority//第一种方式//         List<GrantedAuthority> newList = new ArrayList<>();//        for (String permission : permissions) {//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);//            newList.add(authority);//        }//方式二
      authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());return authorities;}@OverridepublicStringgetPassword(){return user.getPassword();}@OverridepublicStringgetUsername(){return user.getUserName();}@OverridepublicbooleanisAccountNonExpired(){returntrue;}@OverridepublicbooleanisAccountNonLocked(){returntrue;}@OverridepublicbooleanisCredentialsNonExpired(){returntrue;}@OverridepublicbooleanisEnabled(){returntrue;}}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JR7XbX2e-1648310991192)(C:\Users\30666\AppData\Roaming\Typora\typora-user-images\image-20220326193136483.png)]

​ LoginUser修改完后我们就可以在UserDetailsServiceImpl中去把权限信息封装到LoginUser中了。我们写死权限进行测试,后面我们再从数据库中查询权限信息。

packagecom.qx.service.impl;importcom.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;importcom.qx.entity.LoginUser;importcom.qx.entity.User;importcom.qx.mapper.MenuMapper;importcom.qx.mapper.UserMapper;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.stereotype.Service;importjava.util.List;importjava.util.Objects;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@ServicepublicclassUserDetailsServiceImplimplementsUserDetailsService{@AutowiredprivateUserMapper userMapper;//实现UserDetailsService接口,重写UserDetails方法,自定义用户的信息从数据中查询@OverridepublicUserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException{//(认证,即校验该用户是否存在)查询用户信息LambdaQueryWrapper<User> queryWrapper =newLambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);User user = userMapper.selectOne(queryWrapper);//如果没有查询到用户if(Objects.isNull(user)){thrownewRuntimeException("用户名或者密码错误");}//TODO (授权,即查询用户具有哪些权限)查询对应的用户信息//定义一个权限集合List<String> list =newArrayList<String>(Arrays.asList("test","admin"));//把数据封装成UserDetails返回returnnewLoginUser(user,list);}}

5.3.3 从数据库查询权限信息

5.3.3.1 RBAC权限模型

​ RBAC权限模型(Role-Based Access Control)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。
在这里插入图片描述

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:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8x3RslqQ-1648310991193)(https://raw.githubusercontent.com/qiyuank/MyTypore/master/img/image-20220326194432621.png)]

sys_role:

image-20220326194503761

sys_role_menu:

image-20220326194527618

sys_menu:

image-20220326194639403

CREATEDATABASE/*!32312 IF NOT EXISTS*/`sg_security`/*!40100 DEFAULT CHARACTER SET utf8mb4 */;USE`sg_security`;/*Table structure for table `sys_menu` */DROPTABLEIFEXISTS`sys_menu`;CREATETABLE`sys_menu`(`id`bigint(20)NOTNULLAUTO_INCREMENT,`menu_name`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'菜单名',`path`varchar(200)DEFAULTNULLCOMMENT'路由地址',`component`varchar(255)DEFAULTNULLCOMMENT'组件路径',`visible`char(1)DEFAULT'0'COMMENT'菜单状态(0显示 1隐藏)',`status`char(1)DEFAULT'0'COMMENT'菜单状态(0正常 1停用)',`perms`varchar(100)DEFAULTNULLCOMMENT'权限标识',`icon`varchar(100)DEFAULT'#'COMMENT'菜单图标',`create_by`bigint(20)DEFAULTNULL,`create_time`datetimeDEFAULTNULL,`update_by`bigint(20)DEFAULTNULL,`update_time`datetimeDEFAULTNULL,`del_flag`int(11)DEFAULT'0'COMMENT'是否删除(0未删除 1已删除)',`remark`varchar(500)DEFAULTNULLCOMMENT'备注',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8mb4 COMMENT='菜单表';/*Table structure for table `sys_role` */DROPTABLEIFEXISTS`sys_role`;CREATETABLE`sys_role`(`id`bigint(20)NOTNULLAUTO_INCREMENT,`name`varchar(128)DEFAULTNULL,`role_key`varchar(100)DEFAULTNULLCOMMENT'角色权限字符串',`status`char(1)DEFAULT'0'COMMENT'角色状态(0正常 1停用)',`del_flag`int(1)DEFAULT'0'COMMENT'del_flag',`create_by`bigint(200)DEFAULTNULL,`create_time`datetimeDEFAULTNULL,`update_by`bigint(200)DEFAULTNULL,`update_time`datetimeDEFAULTNULL,`remark`varchar(500)DEFAULTNULLCOMMENT'备注',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8mb4 COMMENT='角色表';/*Table structure for table `sys_role_menu` */DROPTABLEIFEXISTS`sys_role_menu`;CREATETABLE`sys_role_menu`(`role_id`bigint(200)NOTNULLAUTO_INCREMENTCOMMENT'角色ID',`menu_id`bigint(200)NOTNULLDEFAULT'0'COMMENT'菜单id',PRIMARYKEY(`role_id`,`menu_id`))ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8mb4;/*Table structure for table `sys_user` */DROPTABLEIFEXISTS`sys_user`;CREATETABLE`sys_user`(`id`bigint(20)NOTNULLAUTO_INCREMENTCOMMENT'主键',`user_name`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'用户名',`nick_name`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'昵称',`password`varchar(64)NOTNULLDEFAULT'NULL'COMMENT'密码',`status`char(1)DEFAULT'0'COMMENT'账号状态(0正常 1停用)',`email`varchar(64)DEFAULTNULLCOMMENT'邮箱',`phonenumber`varchar(32)DEFAULTNULLCOMMENT'手机号',`sex`char(1)DEFAULTNULLCOMMENT'用户性别(0男,1女,2未知)',`avatar`varchar(128)DEFAULTNULLCOMMENT'头像',`user_type`char(1)NOTNULLDEFAULT'1'COMMENT'用户类型(0管理员,1普通用户)',`create_by`bigint(20)DEFAULTNULLCOMMENT'创建人的用户id',`create_time`datetimeDEFAULTNULLCOMMENT'创建时间',`update_by`bigint(20)DEFAULTNULLCOMMENT'更新人',`update_time`datetimeDEFAULTNULLCOMMENT'更新时间',`del_flag`int(11)DEFAULT'0'COMMENT'删除标志(0代表未删除,1代表已删除)',PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=3DEFAULTCHARSET=utf8mb4 COMMENT='用户表';/*Table structure for table `sys_user_role` */DROPTABLEIFEXISTS`sys_user_role`;CREATETABLE`sys_user_role`(`user_id`bigint(200)NOTNULLAUTO_INCREMENTCOMMENT'用户id',`role_id`bigint(200)NOTNULLDEFAULT'0'COMMENT'角色id',PRIMARYKEY(`user_id`,`role_id`))ENGINE=InnoDBDEFAULTCHARSET=utf8mb4;

查询用户具有什么权限得sql语句:

# 根据userid 查询perms 对应的role和menu 都必须是正常状态selectdistinct m.perms from sys_user_role ur
leftjoin sys_role r on ur.role_id=r.id
leftjoin sys_role_menu rm on ur.role_id=rm.role_id
leftjoin sys_menu m on m.id=rm.menu_id
where user_id=2and r.status=0and m.status=0

实体类:

Menu
packagecom.qx.entity;importcom.baomidou.mybatisplus.annotation.TableId;importcom.baomidou.mybatisplus.annotation.TableName;importcom.fasterxml.jackson.annotation.JsonInclude;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;importjava.io.Serializable;importjava.util.Date;/**
 * 菜单表(Menu)实体类
 *
 */@TableName(value="sys_menu")@Data@AllArgsConstructor@NoArgsConstructor@JsonInclude(JsonInclude.Include.NON_NULL)publicclassMenuimplementsSerializable{privatestaticfinallong serialVersionUID =-54979041104113736L;@TableIdprivateLong id;/**
    * 菜单名
    */privateString menuName;/**
    * 路由地址
    */privateString path;/**
    * 组件路径
    */privateString component;/**
    * 菜单状态(0显示 1隐藏)
    */privateString visible;/**
    * 菜单状态(0正常 1停用)
    */privateString status;/**
    * 权限标识
    */privateString perms;/**
    * 菜单图标
    */privateString icon;privateLong createBy;privateDate createTime;privateLong updateBy;privateDate updateTime;/**
    * 是否删除(0未删除 1已删除)
    */privateInteger delFlag;/**
    * 备注
    */privateString remark;}
5.3.3.3、代码实现

​ 我们只需要根据用户id去查询到其所对应的权限信息即可。

​ 所以我们可以先定义个mapper,其中提供一个方法可以根据userid查询权限信息。

MenuMapper
packagecom.qx.mapper;importcom.baomidou.mybatisplus.core.mapper.BaseMapper;importcom.qx.entity.Menu;importorg.apache.ibatis.annotations.Mapper;importorg.springframework.stereotype.Repository;importjava.util.List;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@Mapper@RepositorypublicinterfaceMenuMapperextendsBaseMapper<Menu>{List<String>selectPermsByUserId(Long userid);}
创建对应的Mapper.xml文件,定义对应的sql语句

MenuMapper.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.qx.mapper.MenuMapper"><selectid="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=UTCusername: root
    password:123456driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:mapper-locations: classpath*:/mapper/**/*.xmlserver:port:8888

然后我们可以在UserDetailsServiceImpl中去调用该mapper的方法查询权限信息封装到LoginUser对象中即可。

packagecom.qx.service.impl;importcom.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;importcom.qx.entity.LoginUser;importcom.qx.entity.User;importcom.qx.mapper.MenuMapper;importcom.qx.mapper.UserMapper;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.security.core.userdetails.UserDetails;importorg.springframework.security.core.userdetails.UserDetailsService;importorg.springframework.security.core.userdetails.UsernameNotFoundException;importorg.springframework.stereotype.Service;importjava.util.List;importjava.util.Objects;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@ServicepublicclassUserDetailsServiceImplimplementsUserDetailsService{@AutowiredprivateUserMapper userMapper;@AutowiredprivateMenuMapper menuMapper;//实现UserDetailsService接口,重写UserDetails方法,自定义用户的信息从数据中查询@OverridepublicUserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException{//(认证,即校验该用户是否存在)查询用户信息LambdaQueryWrapper<User> queryWrapper =newLambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);User user = userMapper.selectOne(queryWrapper);//如果没有查询到用户if(Objects.isNull(user)){thrownewRuntimeException("用户名或者密码错误");}//TODO (授权,即查询用户具有哪些权限)查询对应的用户信息//定义一个权限集合//        List<String> list = new ArrayList<String>(Arrays.asList("test","admin"));List<String> list = menuMapper.selectPermsByUserId(user.getId());//把数据封装成UserDetails返回returnnewLoginUser(user,list);}}

测试:

packagecom.qx.controller;importorg.springframework.security.access.prepost.PreAuthorize;importorg.springframework.security.core.parameters.P;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@RestControllerpublicclassHelloController{@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')")publicStringhello(){return"hello";}}

6、自定义失败处理

​ 我们还希望在认证失败或者是授权失败的情况下也能和我们的接口一样返回相同结构的json,这样可以让前端能对响应进行统一的处理。要实现这个功能我们需要知道SpringSecurity的异常处理机制。

​ 在SpringSecurity中,如果我们在认证或者授权的过程中出现了异常会被ExceptionTranslationFilter捕获到。在ExceptionTranslationFilter中会去判断是认证失败还是授权失败出现的异常。

​ 如果是认证过程中出现的异常会被封装成AuthenticationException然后调用

AuthenticationEntryPoint

对象的方法去进行异常处理。

​ 如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用

AccessDeniedHandler

对象的方法去进行异常处理。

​ 所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可。

6.1、自定义实现类

AuthenticationEntryPointImpl
packagecom.qx.handler;importcom.alibaba.fastjson.JSON;importcom.qx.controller.ResponseResult;importcom.qx.utils.WebUtils;importorg.springframework.http.HttpStatus;importorg.springframework.security.core.AuthenticationException;importorg.springframework.security.web.AuthenticationEntryPoint;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc : 认证的异常处理类
 */@ComponentpublicclassAuthenticationEntryPointImplimplementsAuthenticationEntryPoint{@Overridepublicvoidcommence(HttpServletRequest request,HttpServletResponse response,AuthenticationException authException)throwsIOException,ServletException{ResponseResult result =newResponseResult(HttpStatus.UNAUTHORIZED.value(),"用户名认证失败请重新登录");String json = JSON.toJSONString(result);//处理移除WebUtils.renderString(response,json);}}
AccessDeniedHandlerImpl
packagecom.qx.handler;importcom.alibaba.fastjson.JSON;importcom.qx.controller.ResponseResult;importcom.qx.utils.WebUtils;importorg.springframework.http.HttpStatus;importorg.springframework.security.access.AccessDeniedException;importorg.springframework.security.web.access.AccessDeniedHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc : 授权的异常处理
 */@ComponentpublicclassAccessDeniedHandlerImplimplementsAccessDeniedHandler{@Overridepublicvoidhandle(HttpServletRequest request,HttpServletResponse response,AccessDeniedException accessDeniedException)throwsIOException,ServletException{ResponseResult result =newResponseResult(HttpStatus.FORBIDDEN.value(),"您的权限不足");String json = JSON.toJSONString(result);//处理移除WebUtils.renderString(response,json);}}

6.2、配置给SpringSecurity

@AutowiredprivateAuthenticationEntryPoint authenticationEntryPoint;@AutowiredprivateAccessDeniedHandler accessDeniedHandler;

接着我们就可以使用HttpSecurity对象的方法去配置。

//配置异常处理器
http.exceptionHandling()//认证失败处理器.authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler);

7、 跨域

​ 浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求,默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。

​ 前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。

​ 所以我们就要处理一下,让前端能进行跨域请求。

SpringBoot配置,运行跨域请求
CorsConfig
packagecom.qx.config;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.CorsRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ConfigurationpublicclassCorsConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistry registry){// 设置允许跨域的路径
        registry.addMapping("/**")// 设置允许跨域请求的域名.allowedOriginPatterns("*")// 是否允许cookie.allowCredentials(true)// 设置允许的请求方式.allowedMethods("GET","POST","DELETE","PUT")// 设置允许的header属性.allowedHeaders("*")// 跨域允许时间.maxAge(3600);}}
在SecurityConfig中开启开启SpringSecurity的跨域访问

由于我们的资源都会收到SpringSecurity的保护,所以想要跨域访问还要让SpringSecurity运行跨域访问。

packagecom.qx.config;importcom.qx.filter.JwtAuthenticationTokenFilter;importcom.qx.handler.AccessDeniedHandlerImpl;importcom.qx.handler.AuthenticationEntryPointImpl;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.config.http.SessionCreationPolicy;importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;importorg.springframework.security.crypto.password.PasswordEncoder;importorg.springframework.security.web.AuthenticationEntryPoint;importorg.springframework.security.web.access.AccessDeniedHandler;importorg.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;importsun.security.util.Password;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@Configuration@EnableGlobalMethodSecurity(prePostEnabled =true)//开启授权注解功能publicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@AutowiredprivateJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;@AutowiredprivateAuthenticationEntryPoint authenticationEntryPoint;@AutowiredprivateAccessDeniedHandler accessDeniedHandler;//放行@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        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@OverrideprotectedAuthenticationManagerauthenticationManager()throwsException{returnsuper.authenticationManager();}}

8、自定义权限校验方法

我们也可以定义自己的权限校验方法,在@PreAuthorize注解中使用我们的方法。

packagecom.qx.expression;importcom.qx.entity.LoginUser;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.context.SecurityContextHolder;importorg.springframework.stereotype.Component;importjava.util.List;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@Component("ex")publicclassQXExpressionRoot{//String authority 这里是后端赋给它的权限//从数据库获取登录用户的权限功能  和authority 进行对比publicbooleanhasAuthority(String authority){//获取当前用户得权限Authentication authentication =SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser =(LoginUser) authentication.getPrincipal();List<String> permissions = loginUser.getPermissions();//判断用户权限集合中是否存在  authorityreturn permissions.contains(authority);}}

在SPEL表达式中使用 @ex相当于获取容器中bean的名字为ex的对象。然后再调用这个对象的hasAuthority方法

@RequestMapping("hello")//自定义的权限功能@PreAuthorize("@ex.hasAuthority('system:dept:list')")publicStringhello(){return"hello";}
基于配置的权限控制
packagecom.qx.config;importcom.qx.filter.JwtAuthenticationTokenFilter;importcom.qx.handler.AccessDeniedHandlerImpl;importcom.qx.handler.AuthenticationEntryPointImpl;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.config.http.SessionCreationPolicy;importorg.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;importorg.springframework.security.crypto.password.PasswordEncoder;importorg.springframework.security.web.AuthenticationEntryPoint;importorg.springframework.security.web.access.AccessDeniedHandler;importorg.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;importsun.security.util.Password;/**
 * @author : k
 * @Date : 2022/3/23
 * @Desc :
 */@Configuration@EnableGlobalMethodSecurity(prePostEnabled =true)//开启授权注解功能publicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@BeanpublicPasswordEncoderpasswordEncoder(){returnnewBCryptPasswordEncoder();}@AutowiredprivateJwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;@AutowiredprivateAuthenticationEntryPoint authenticationEntryPoint;@AutowiredprivateAccessDeniedHandler accessDeniedHandler;//放行@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        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@OverrideprotectedAuthenticationManagerauthenticationManager()throwsException{returnsuper.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
packagecom.qx.handler;importorg.springframework.security.core.Authentication;importorg.springframework.security.web.authentication.AuthenticationSuccessHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ComponentpublicclassQXSuccessHandlerimplementsAuthenticationSuccessHandler{@OverridepublicvoidonAuthenticationSuccess(HttpServletRequest request,HttpServletResponse response,Authentication authentication)throwsIOException,ServletException{System.out.println("认证成功");}}
SecurityConfig
packagecom.qx.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.web.authentication.AuthenticationFailureHandler;importorg.springframework.security.web.authentication.AuthenticationSuccessHandler;importorg.springframework.security.web.authentication.logout.LogoutSuccessHandler;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@AutowiredprivateAuthenticationSuccessHandler authencationSuccessHandler;@AutowiredprivateAuthenticationFailureHandler authencationFailureHandler;@AutowiredprivateLogoutSuccessHandler logoutSuccessHandler;@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http.formLogin().//配置认证成功处理器successHandler(authencationSuccessHandler)//配置认证失败处理器.failureHandler(authencationFailureHandler);//配置注销成功处理器
        http.logout().logoutSuccessHandler(logoutSuccessHandler);//因为重写了 所以需要手动添加认证规则
        http.authorizeRequests().anyRequest().authenticated();}}

10.2、认证失败处理器

QXFailureHandler
packagecom.qx.handler;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.AuthenticationException;importorg.springframework.security.web.authentication.AuthenticationFailureHandler;importorg.springframework.security.web.authentication.AuthenticationSuccessHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ComponentpublicclassQXFailureHandlerimplementsAuthenticationFailureHandler{@OverridepublicvoidonAuthenticationFailure(HttpServletRequest request,HttpServletResponse response,AuthenticationException exception)throwsIOException,ServletException{System.out.println("认证失败");}}
SecurityConfig
packagecom.qx.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.web.authentication.AuthenticationFailureHandler;importorg.springframework.security.web.authentication.AuthenticationSuccessHandler;importorg.springframework.security.web.authentication.logout.LogoutSuccessHandler;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@AutowiredprivateAuthenticationSuccessHandler authencationSuccessHandler;@AutowiredprivateAuthenticationFailureHandler authencationFailureHandler;@AutowiredprivateLogoutSuccessHandler logoutSuccessHandler;@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http.formLogin().//配置认证成功处理器successHandler(authencationSuccessHandler)//配置认证失败处理器.failureHandler(authencationFailureHandler);//配置注销成功处理器
        http.logout().logoutSuccessHandler(logoutSuccessHandler);//因为重写了 所以需要手动添加认证规则
        http.authorizeRequests().anyRequest().authenticated();}}

10.3、注销成功处理器

QXLogoutSuccessHandler
packagecom.qx.handler;importorg.springframework.security.core.Authentication;importorg.springframework.security.web.authentication.logout.LogoutSuccessHandler;importorg.springframework.stereotype.Component;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ComponentpublicclassQXLogoutSuccessHandlerimplementsLogoutSuccessHandler{@OverridepublicvoidonLogoutSuccess(HttpServletRequest request,HttpServletResponse response,Authentication authentication)throwsIOException,ServletException{System.out.println("注销成功");}}
SecurityConfig
packagecom.qx.config;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.annotation.Configuration;importorg.springframework.security.config.annotation.web.builders.HttpSecurity;importorg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;importorg.springframework.security.web.authentication.AuthenticationFailureHandler;importorg.springframework.security.web.authentication.AuthenticationSuccessHandler;importorg.springframework.security.web.authentication.logout.LogoutSuccessHandler;/**
 * @author : k
 * @Date : 2022/3/24
 * @Desc :
 */@ConfigurationpublicclassSecurityConfigextendsWebSecurityConfigurerAdapter{@AutowiredprivateAuthenticationSuccessHandler authencationSuccessHandler;@AutowiredprivateAuthenticationFailureHandler authencationFailureHandler;@AutowiredprivateLogoutSuccessHandler logoutSuccessHandler;@Overrideprotectedvoidconfigure(HttpSecurity http)throwsException{
        http.formLogin().//配置认证成功处理器successHandler(authencationSuccessHandler)//配置认证失败处理器.failureHandler(authencationFailureHandler);//配置注销成功处理器
        http.logout().logoutSuccessHandler(logoutSuccessHandler);//因为重写了 所以需要手动添加认证规则
        http.authorizeRequests().anyRequest().authenticated();}}

彩蛋:

1、SecurityContextHolder:用于存储安全上下文SecurityContext信息,而这个SecurityContexr进一步持有Authentication 即代表的是当前的用户的所有信息:该用户是谁,是否已经被认证,拥有哪些角色…这些信息都被保存在Anthentication中。

image-20220325145125354

SecurityContextHolder默认使用ThreadLocal 策略来存储认证信息,也就是说这是一种线程绑定信息的策略,Spring Security在用户登录时自动绑定认证信息到当前的线程,在用户退出时,自动清楚当前线程的认证信息。

2、Authentication

packageorg.springframework.security.core;importjava.io.Serializable;importjava.security.Principal;importjava.util.Collection;importorg.springframework.security.authentication.AuthenticationManager;importorg.springframework.security.core.context.SecurityContextHolder;publicinterfaceAuthenticationextendsPrincipal,Serializable{//权限   集合中放的 是GrantedAuthority的子类  SimpleGrantedAuthorityCollection<?extendsGrantedAuthority>getAuthorities();ObjectgetCredentials();//获取凭证信息,也就是获取密码ObjectgetDetails();//获取详细信息 比如ip adress等都保存在Details中ObjectgetPrincipal();//获取主题Principal 用户的详细信息 一个Object对象booleanisAuthenticated();//是否已认证voidsetAuthenticated(boolean isAuthenticated)throwsIllegalArgumentException;//set方法}

3、

GrantedAuthority
packageorg.springframework.security.core;importjava.io.Serializable;importorg.springframework.security.access.AccessDecisionManager;publicinterfaceGrantedAuthorityextendsSerializable{StringgetAuthority();//得到认证}
简单的授权认证,权限
packageorg.springframework.security.core.authority;importorg.springframework.security.core.GrantedAuthority;importorg.springframework.security.core.SpringSecurityCoreVersion;importorg.springframework.util.Assert;publicfinalclassSimpleGrantedAuthorityimplementsGrantedAuthority{privatefinalString role;publicSimpleGrantedAuthority(String role){Assert.hasText(role,"A granted authority textual representation is required");this.role = role;}@OverridepublicStringgetAuthority(){returnthis.role;}

image-20220325150210749

也就是说GrantedAuthority里边存放的就是Authority 权限对象

4、UserDetails

packageorg.springframework.security.core.userdetails;importjava.io.Serializable;importjava.util.Collection;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.GrantedAuthority;publicinterfaceUserDetailsextendsSerializable{Collection<?extendsGrantedAuthority>getAuthorities();//权限标识集合StringgetPassword();//密码StringgetUsername();//用户名booleanisAccountNonExpired();//是否未过期booleanisAccountNonLocked();//是否未锁定booleanisCredentialsNonExpired();//凭证是否未过期booleanisEnabled();//是否可用}

5、UserDetailsService

publicinterfaceUserDetailsService{//通过username  查询 UserDetails UserDetailsloadUserByUsername(String username)throwsUsernameNotFoundException;}

6、AuthenticationManager 认证管理器

publicinterfaceAuthenticationManager{//authenticate鉴定   对传入的authentication进行认证 Authenticationauthenticate(Authentication authentication)throwsAuthenticationException;}

7、ProviderManager 是AuthenticationManager的实现类

packageorg.springframework.security.authentication;importjava.util.Arrays;importjava.util.Collections;importjava.util.List;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importorg.springframework.beans.factory.InitializingBean;importorg.springframework.context.MessageSource;importorg.springframework.context.MessageSourceAware;importorg.springframework.context.support.MessageSourceAccessor;importorg.springframework.core.log.LogMessage;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.AuthenticationException;importorg.springframework.security.core.CredentialsContainer;importorg.springframework.security.core.SpringSecurityMessageSource;importorg.springframework.util.Assert;importorg.springframework.util.CollectionUtils;publicclassProviderManagerimplementsAuthenticationManager,MessageSourceAware,InitializingBean{privatestaticfinalLog logger =LogFactory.getLog(ProviderManager.class);privateAuthenticationEventPublisher eventPublisher =newNullEventPublisher();privateList<AuthenticationProvider> providers =Collections.emptyList();protectedMessageSourceAccessor messages =SpringSecurityMessageSource.getAccessor();privateAuthenticationManager parent;privateboolean eraseCredentialsAfterAuthentication =true;publicProviderManager(AuthenticationProvider... providers){this(Arrays.asList(providers),null);}publicProviderManager(List<AuthenticationProvider> providers){this(providers,null);}publicProviderManager(List<AuthenticationProvider> providers,AuthenticationManager parent){Assert.notNull(providers,"providers list cannot be null");this.providers = providers;this.parent = parent;checkState();}@OverridepublicvoidafterPropertiesSet(){checkState();}privatevoidcheckState(){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接口的方法 重点@OverridepublicAuthenticationauthenticate(Authentication authentication)throwsAuthenticationException{Class<?extendsAuthentication> 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 statusthrow 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 instanceofCredentialsContainer)){// 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 itif(parentResult ==null){this.eventPublisher.publishAuthenticationSuccess(result);}return result;}// Parent was null, or didn't authenticate (or throw an exception).if(lastException ==null){
         lastException =newProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",newObject[]{ 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 itif(parentException ==null){prepareException(lastException, authentication);}throw lastException;}@SuppressWarnings("deprecation")privatevoidprepareException(AuthenticationException ex,Authentication auth){this.eventPublisher.publishAuthenticationFailure(ex, auth);}privatevoidcopyDetails(Authentication source,Authentication dest){if((dest instanceofAbstractAuthenticationToken)&&(dest.getDetails()==null)){AbstractAuthenticationToken token =(AbstractAuthenticationToken) dest;
         token.setDetails(source.getDetails());}}publicList<AuthenticationProvider>getProviders(){returnthis.providers;}@OverridepublicvoidsetMessageSource(MessageSource messageSource){this.messages =newMessageSourceAccessor(messageSource);}publicvoidsetAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher){Assert.notNull(eventPublisher,"AuthenticationEventPublisher cannot be null");this.eventPublisher = eventPublisher;}publicvoidsetEraseCredentialsAfterAuthentication(boolean eraseSecretData){this.eraseCredentialsAfterAuthentication = eraseSecretData;}publicbooleanisEraseCredentialsAfterAuthentication(){returnthis.eraseCredentialsAfterAuthentication;}privatestaticfinalclassNullEventPublisherimplementsAuthenticationEventPublisher{@OverridepublicvoidpublishAuthenticationFailure(AuthenticationException exception,Authentication authentication){}@OverridepublicvoidpublishAuthenticationSuccess(Authentication authentication){}}}

8、AuthenticationProvider

packageorg.springframework.security.authentication;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.AuthenticationException;publicinterfaceAuthenticationProvider{//认证 AuthenticationAuthenticationauthenticate(Authentication authentication)throwsAuthenticationException;//是否支持传入authenticationbooleansupports(Class<?> authentication);}}}if(result !=null){if(this.eraseCredentialsAfterAuthentication &&(result instanceofCredentialsContainer)){// 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 itif(parentResult ==null){this.eventPublisher.publishAuthenticationSuccess(result);}return result;}// Parent was null, or didn't authenticate (or throw an exception).if(lastException ==null){
         lastException =newProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound",newObject[]{ 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 itif(parentException ==null){prepareException(lastException, authentication);}throw lastException;}@SuppressWarnings("deprecation")privatevoidprepareException(AuthenticationException ex,Authentication auth){this.eventPublisher.publishAuthenticationFailure(ex, auth);}privatevoidcopyDetails(Authentication source,Authentication dest){if((dest instanceofAbstractAuthenticationToken)&&(dest.getDetails()==null)){AbstractAuthenticationToken token =(AbstractAuthenticationToken) dest;
         token.setDetails(source.getDetails());}}publicList<AuthenticationProvider>getProviders(){returnthis.providers;}@OverridepublicvoidsetMessageSource(MessageSource messageSource){this.messages =newMessageSourceAccessor(messageSource);}publicvoidsetAuthenticationEventPublisher(AuthenticationEventPublisher eventPublisher){Assert.notNull(eventPublisher,"AuthenticationEventPublisher cannot be null");this.eventPublisher = eventPublisher;}publicvoidsetEraseCredentialsAfterAuthentication(boolean eraseSecretData){this.eraseCredentialsAfterAuthentication = eraseSecretData;}publicbooleanisEraseCredentialsAfterAuthentication(){returnthis.eraseCredentialsAfterAuthentication;}privatestaticfinalclassNullEventPublisherimplementsAuthenticationEventPublisher{@OverridepublicvoidpublishAuthenticationFailure(AuthenticationException exception,Authentication authentication){}@OverridepublicvoidpublishAuthenticationSuccess(Authentication authentication){}}}

8、AuthenticationProvider

packageorg.springframework.security.authentication;importorg.springframework.security.core.Authentication;importorg.springframework.security.core.AuthenticationException;publicinterfaceAuthenticationProvider{//认证 AuthenticationAuthenticationauthenticate(Authentication authentication)throwsAuthenticationException;//是否支持传入authenticationbooleansupports(Class<?> authentication);}

本文转载自: https://blog.csdn.net/weixin_50569789/article/details/123766739
版权归原作者 动次哒从 所有, 如有侵权,请联系我们删除。

“SpringSecurity框架【详解】”的评论:

还没有评论