Spring Security-从入门到精通(全网最全)

Spring Security-从入门到精通

课程介绍

Spring Security是spring家族中一个安全管理框架,相比其他安全框架Shiro,提供更丰富的功能,社区资源丰富

中大型项目使用Spring Security来作安全框架,小项目使用shiro;相比较Spring Security,shiro上手简单。

一般web应用需要进行认证和授权

认证:验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户 授权:判断登录后的用户是否有权限进行某个操作

认证和授权是SpringSecurity作为安全框架核心功能。

1 简介

2 快速入门

快速搭建一个简单springboot工程

设置父工程,添加依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.geekmice</groupId>
    <artifactId>springsecurityquickstart</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecurityquickstart</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

创建启动类

package com.geekmice.springsecurityquickstart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringsecurityquickstartApplication {
          
   

    public static void main(String[] args) {
          
   
        SpringApplication.run(SpringsecurityquickstartApplication.class, args);
    }

}

创建控制层controller

package com.geekmice.springsecurityquickstart.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
          
   

    @GetMapping("/hello")
    public String hello(){
          
   
        return "hello";
    }
}

引入spring security

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

访问接口情况,出现登录页面

用户名:user 密码:f9ab8778-f0a5-4bf3-a492-61b92ed55c76

默认登录页面

3 认证

3.1 登录校验流程

3.2 原理分析

分析需要修改的地方

想要知道如何实现自己的登录流程就必须知道入门案例springsecurity流程

3.2.1 完整流程

springsecurity原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器,这里我们可以看看入门案例中的过滤器

图中只是展示核心过滤器,其他的非核心过滤器没有图中展示

UsernamePasswordAuthenticationFilter:负责处理我们登录页面填写用户名秘密之后登录请求,入门案例的认证工作由它负责

ExceptionTranslationFilter:处理过滤器链中抛出任何AccessDeniedException和AuthenticationException

FilterSecurityInterceptor:负责权限校验的过滤器

我们可以通过Debug查看当前系统中SpringSecurity过滤器链有哪些过滤器以及它们的顺序

如何查看过滤器链

ConfigurableApplicationContext run = SpringApplication.run(SpringsecurityquickstartApplication.class, args);
System.out.println(22);

3.2.2 认证流程分析

3.3 思路分析

登录

Authentication接口:它的实现类,表示当前访问系统的用户,封装用户详细信息

AuthenticationManager接口:定义认证Authentication的方法

UserDetailsService接口:加载用户特定数据的核心接口,里面定义了一个根据用户名查询用户信息的方法

UserDetails接口:提供核心用户信息,通过UserDetailsService根据用户名获取处理的用户信息封装成UserDetails对象返回,然后将这些信息封装到Authentication对象中

校验

总结

登录 自定义登录接口 调用ProviderManager的方法进行认证,如果认证通过生成jwt 把用户信息存入redis 自定义UserDetailsService 查询数据库 校验 定义JWT过滤器 获取token 解析token获取其中userid 从redis获取用户信息 存入SecurityContextHolder

3.4 解决问题

3.4.1 准备工作

需要的依赖

<!--redis依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--fastjson依赖-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.33</version>
</dependency>
<!--jwt依赖-->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.0</version>
</dependency>

添加序列化,redis相关配置

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;

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<?> clazz)
    {
          
   
        return TypeFactory.defaultInstance().constructType(clazz);
    }
}
import com.tigerhhzz.utils.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
*
* @author tigerhhzz
* @date 2022/5/27 11:27
*
*/

@Configuration
public class RedisConfig {
          
   

    @Bean
    @SuppressWarnings(value = {
          
    "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
          
   
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

响应类 ResponseResult

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> {
          
   
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 提示信息,如果有错误时,前端可以获取该字段进行提示
     */
    private String msg;
    /**
     * 查询到的结果数据,
     */
    private T data;

    public ResponseResult(Integer code, String msg) {
          
   
        this.code = code;
        this.msg = msg;
    }

    public ResponseResult(Integer code, T data) {
          
   
        this.code = code;
        this.data = data;
    }

    public Integer getCode() {
          
   
        return code;
    }

    public void setCode(Integer code) {
          
   
        this.code = code;
    }

    public String getMsg() {
          
   
        return msg;
    }

    public void setMsg(String msg) {
          
   
        this.msg = msg;
    }

    public T getData() {
          
   
        return data;
    }

    public void setData(T data) {
          
   
        this.data = data;
    }

    public ResponseResult(Integer code, String msg, T data) {
          
   
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
}

工具类 JwtUtils,WebUtils,RedisCache

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
          
   

    //有效期为
    public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000  一个小时
    //设置秘钥明文
    public static final String JWT_KEY = "sangeng";

    public static String getUUID(){
          
   
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @return
     */
    public static String createJWT(String subject) {
          
   
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据(json格式)
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
          
   
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
          
   
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
          
   
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
          
   
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    public static void main(String[] args) throws Exception {
          
   
//        String jwt = createJWT("123456");

        Claims claims1 = JwtUtil.parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzNTQ5MzQyNmMyYzA0YzBjOTI0OGM1NmZkYTAyODk5YSIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY1ODY0MDcxMiwiZXhwIjoxNjU4NjQ0MzEyfQ.3cnm12voQEmc_2XcJp-Co4EUeU8FDtaoF53uV8Zhg3s");
        System.out.println(claims1.getSubject());
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
          
   
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
          
   
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


}

RedisCache

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

@SuppressWarnings(value = {
          
    "unchecked", "rawtypes" })
@Component
public class RedisCache
{
          
   
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
          
   
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
          
   
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
          
   
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
          
   
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
          
   
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
          
   
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection)
    {
          
   
        return redisTemplate.delete(collection);
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
          
   
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
          
   
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<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(final String key)
    {
          
   
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
          
   
        if (dataMap != null) {
          
   
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
          
   
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
          
   
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
          
   
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 删除Hash中的数据
     *
     * @param key
     * @param hkey
     */
    public void delCacheMapValue(final String key, final String hkey)
    {
          
   
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(key, hkey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
          
   
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
          
   
        return redisTemplate.keys(pattern);
    }
}

WebUtils

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WebUtils
{
          
   
    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string 待渲染的字符串
     * @return null
     */
    public static String renderString(HttpServletResponse response, String string) {
          
   
        try
        {
          
   
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
          
   
            e.printStackTrace();
        }
        return null;
    }
}

3.4.2 实现

数据库校验用户

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

创建用户表

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=2 DEFAULT CHARSET=utf8mb4 COMMENT=用户表

引入MybatisPuls和mysql驱动的依赖

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.4.3</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置数据库信息

spring:
  datasource:
    url: jdbc:mysql://192.168.244.8:3306/school?characterEncoding=utf-8&serverTimezone=UTC
    username: *
    password: *
    driver-class-name: com.mysql.cj.jdbc.Driver

定义mapper接口

public interface UserMapper extends BaseMapper<User> {
          
   
}

User实体类

package com.geekmice.springsecuritytokendemo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.Setter;

/**
 * <p>
 * 用户表
 * </p>
 *
 * @since 2022-10-16
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user")
public class User implements Serializable {
          
   

    private static final long serialVersionUID = 1L;

      /**
     * 主键
     */
        @TableId(value = "id", type = IdType.AUTO)
      private Long id;

      /**
     * 用户名
     */
      private String userName;

      /**
     * 昵称
     */
      private String nickName;

      /**
     * 密码
     */
      private String password;

      /**
     * 账号状态(0正常 1停用)
     */
      private String status;

      /**
     * 邮箱
     */
      private String email;

      /**
     * 手机号
     */
      private String phonenumber;

      /**
     * 用户性别(0男,1女,2未知)
     */
      private String sex;

      /**
     * 头像
     */
      private String avatar;

      /**
     * 用户类型(0管理员,1普通用户)
     */
      private String userType;

      /**
     * 创建人的用户id
     */
      private Long createBy;

      /**
     * 创建时间
     */
      private LocalDateTime createTime;

      /**
     * 更新人
     */
      private Long updateBy;

      /**
     * 更新时间
     */
      private LocalDateTime updateTime;

      /**
     * 删除标志(0代表未删除,1代表已删除)
     */
      private Integer delFlag;


}

配置Mapper扫描

package com.geekmice.springsecuritytokendemo;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.geekmice.springsecuritytokendemo.mapper")
public class SpringsecuritytokendemoApplication {
          
   

    public static void main(String[] args) {
          
   
        SpringApplication.run(SpringsecuritytokendemoApplication.class, args);
    }

}

添加junit依赖

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

测试MP是否能正常使用

package com.geekmice.springsecuritytokendemo;

import com.geekmice.springsecuritytokendemo.entity.User;
import com.geekmice.springsecuritytokendemo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringsecuritytokendemoApplicationTests {
          
   
@Autowired
private UserMapper userMapper;
    @Test
    void contextLoads() {
          
   
        List<User> userList = userMapper.selectList(null);
        System.out.println(userList);
    }
}

核心代码实现

因为UserDetailsService方法的返回值是UserDetails类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。

package com.geekmice.springsecuritytokendemo.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
          
   

    private User user;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
          
   
        return null;
    }

    @Override
    public String getPassword() {
          
   
        return user.getPassword();
    }

    @Override
    public String getUsername() {
          
   
        return user.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
          
   
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
          
   
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
          
   
        return true;
    }

    @Override
    public boolean isEnabled() {
          
   
        return true;
    }
}

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

package com.geekmice.springsecuritytokendemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.geekmice.springsecuritytokendemo.entity.LoginUser;
import com.geekmice.springsecuritytokendemo.entity.User;
import com.geekmice.springsecuritytokendemo.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.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
          
   

    @Autowired
    private UserMapper userMapper;

    @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("用户名或者密码错误");
        }

        return new LoginUser(user);
    }
}
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

解决

这样登陆的时候就可以用sg作为用户名,1234作为密码来登陆了。
注意:如果要测试,需要往用户表中写入用户数据,并且如果你想让用户的密码是明文存储,需要在密码前加{
          
   noop}。例如
密码加密存储

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

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

我们一般使用SpringSecurity为我们提供的BCryptPasswordEncoder。

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

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

package com.geekmice.springsecuritytokendemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
          
   

    @Bean
    public PasswordEncoder passwordEncoder(){
          
   
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
          
   
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 加密方法 encode
        String encodeFirst = bCryptPasswordEncoder.encode("1234");
        String encodeSecond = bCryptPasswordEncoder.encode("1234");
        System.out.println(encodeFirst); // $2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC
        System.out.println(encodeSecond); //  $2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm
        // 判断明文与密文是否一致 matches
        boolean flag = bCryptPasswordEncoder.matches("1234", "$2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm");
        boolean flagSecond = bCryptPasswordEncoder.matches("1234", "$2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC");
        System.out.println(flag); // true
        System.out.println(flagSecond); // true
    }
}

再次验证,效果如下,此时数据库密码是 {noop}1234

Encoded password does not look like BCrypt

jwt工具类使用

public static void main(String[] args) throws Exception {
          
   
        // jwt:加密之後token
       // String jwt = createJWT("123456");
        // System.out.println(jwt);
        // eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3OGE1OGQyYWFjODA0NzlhOGMyNGM3MjdmZmUyYmI1YiIsInN1YiI6IjEyMzQ1NiIsImlzcyI6InNnIiwiaWF0IjoxNjY1OTI3ODM3LCJleHAiOjE2NjU5MzE0Mzd9.y8QcoL3lafXeXHqcGWpMHTvi2RHAB5N3V8a7wdYI0f4
      // 解密 parsetJWT
        Claims claims1 = JwtUtils.parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3OGE1OGQyYWFjODA0NzlhOGMyNGM3MjdmZmUyYmI1YiIsInN1YiI6IjEyMzQ1NiIsImlzcyI6InNnIiwiaWF0IjoxNjY1OTI3ODM3LCJleHAiOjE2NjU5MzE0Mzd9.y8QcoL3lafXeXHqcGWpMHTvi2RHAB5N3V8a7wdYI0f4");
        System.out.println(claims1.getSubject());
    }
登录接口

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

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

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

package com.geekmice.springsecuritytokendemo.controller;

import com.geekmice.springsecuritytokendemo.config.ResponseResult;
import com.geekmice.springsecuritytokendemo.entity.User;
import com.geekmice.springsecuritytokendemo.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
          
   

    @Autowired
    private ILoginService loginService;

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

ILoginService

package com.geekmice.springsecuritytokendemo.service;

import com.geekmice.springsecuritytokendemo.config.ResponseResult;
import com.geekmice.springsecuritytokendemo.entity.User;

public interface ILoginService {
          
   

    ResponseResult login(User user);
}

LoginServiceImpl

package com.geekmice.springsecuritytokendemo.service.impl;

import com.geekmice.springsecuritytokendemo.config.ResponseResult;
import com.geekmice.springsecuritytokendemo.entity.LoginUser;
import com.geekmice.springsecuritytokendemo.entity.User;
import com.geekmice.springsecuritytokendemo.service.ILoginService;
import com.geekmice.springsecuritytokendemo.utils.JwtUtils;
import com.geekmice.springsecuritytokendemo.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements ILoginService {
          
   
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
          
   
        // AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 认证没有通过
        if(Objects.isNull(authenticate)){
          
   
            // 粗略错误提示
            throw new RuntimeException("用户名或者密码错误");
        }
        // 认证通过,通过userid生成jwt,jwt存入响应体
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtils.createJWT(userId);
        // 用户信息存入redis,方便下次使用
        redisCache.setCacheObject("login:"+userId,loginUser);
        // token响应为前端
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登录成功",map);
    }
}

SecurityConfig配置过滤情况

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
          
   

    @Bean
    public PasswordEncoder passwordEncoder(){
          
   
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
          
   
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
          
   
        return super.authenticationManagerBean();
    }
}
认证过滤器

我们需要自定义一个过滤器,这个过滤器会去获取请求头中的token,对token进行解析取出其中的userid。

使用userid去redis中获取对应的LoginUser对象。

然后封装Authentication对象存入SecurityContextHolder

没有携带token访问接口 http://localhost:8080/hello

携带有效token,访问接口http://localhost:8080/hello

自定义jwt过滤器 JwtAuthenticationTokenFilter

package com.geekmice.springsecuritytokendemo.filter;

import com.geekmice.springsecuritytokendemo.entity.LoginUser;
import com.geekmice.springsecuritytokendemo.utils.JwtUtils;
import com.geekmice.springsecuritytokendemo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
          
   
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
          
   
        // 请求头获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
          
   
            // 放行
            filterChain.doFilter(request,response);
            return;
        }

        // 解析token
        String userId;
        try {
          
   
            Claims claims = JwtUtils.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
          
   
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // redis获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
          
   
            throw new RuntimeException("用户未登录");
        }

        // 存入securitycontextholder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null
        );
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request,response);
    }
}

在springsecurity全局配置中添加自定义过滤器jwt

package com.geekmice.springsecuritytokendemo.config;

import com.geekmice.springsecuritytokendemo.filter.JwtAuthenticationTokenFilter;
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.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.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
          
   

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
          
   
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
          
   
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 加密方法 encode
        String encodeFirst = bCryptPasswordEncoder.encode("1234");
        String encodeSecond = bCryptPasswordEncoder.encode("1234");
        System.out.println(encodeFirst); // $2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC
        System.out.println(encodeSecond); //  $2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm
        // 判断明文与密文是否一致 matches
        boolean flag = bCryptPasswordEncoder.matches("1234", "$2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm");
        boolean flagSecond = bCryptPasswordEncoder.matches("1234", "$2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC");
        System.out.println(flag); // true
        System.out.println(flagSecond); // true
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
          
   
        // 关闭csrf
        http.csrf().disable()
                // 不通过session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 登录接口允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除了上面的所有请求均需要鉴权认证
                .anyRequest().authenticated()
        ;
        // 把token校验过滤器添加到过滤器链,在UsernamePasswordAuthenticationFilter前面
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    }

    /**
     * @Description 暴露AuthenticationManager
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
          
   
        return super.authenticationManagerBean();
    }


}
退出登录

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

必须是认证用户调用

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

public interface ILoginService {
          
   

    ResponseResult login(User user);

    ResponseResult logout();
}

serviceimpl
    @Override
    public ResponseResult logout() {
          
   
        // 获取SecurityContextHolder中userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 删除缓存用户信息
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"注销成功");
    }

携带有效token调用注销接口

然后携带有效token再次访问hello

4 授权

4.1 权限系统作用

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

总结起来就是不同的用户可以使用不同的功能。这就是权限系统要去实现的效果。

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

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

4.2 授权基本流程

SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验。在FilterSecurityInterceptor中会从SecurityContextHolder获取其中的Authentication,然后获取其中的权限信息。当前用户是否拥有访问当前资源所需的权限。

所以我们在项目中只需要把当前登录用户的权限信息也存入Authentication。

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

4.3 授权实现

4.3.1 限制访问资源所需要权限

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

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

@EnableGlobalMethodSecurity(prePostEnabled = true)

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

@RestController
public class HelloController {
          
   

    @RequestMapping("/hello")
    @PreAuthorize("hasAuthority(test)")
    public String hello(){
          
   
        return "hello";
    }
}

4.3.2 封装权限信息

问题:autoType is not support. org.springframework.security.core.authority.SimpleGrantedAuthority

redis无法存储对象类型,故而需要禁止序列化操作 @JSONField(serialize=false)

HelloController

package com.geekmice.springsecuritytokendemo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
          
   

    @GetMapping("/hello")
    @PreAuthorize("hasAuthority(test)")
    public String hello() {
          
   
        return "hello";
    }
}

JwtAuthenticationTokenFilter

package com.geekmice.springsecuritytokendemo.filter;

import com.geekmice.springsecuritytokendemo.entity.LoginUser;
import com.geekmice.springsecuritytokendemo.utils.JwtUtils;
import com.geekmice.springsecuritytokendemo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
          
   
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
          
   
        // 请求头获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
          
   
            // 放行
            filterChain.doFilter(request,response);
            return;
        }

        // 解析token
        String userId;
        try {
          
   
            Claims claims = JwtUtils.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
          
   
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // redis获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
          
   
            throw new RuntimeException("用户未登录");
        }

        // 权限信息存入securitycontextholder
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request,response);
    }
}

UserDetailsServiceImpl

package com.geekmice.springsecuritytokendemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.geekmice.springsecuritytokendemo.entity.LoginUser;
import com.geekmice.springsecuritytokendemo.entity.User;
import com.geekmice.springsecuritytokendemo.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.*;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
          
   

    @Autowired
    private UserMapper userMapper;

    @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("用户名或者密码错误");
        }

        // 查询用户权限,暂时权限写死,为了测试使用,test,admin
        List<String> authoritiesList = new ArrayList<>(Arrays.asList("test", "admin"));
        return new LoginUser(user,authoritiesList);
    }
}

登录:jwt过滤器->接口->userdetailserviceimpl处理认证权限

hello: jwt过滤器-对应接口controller->userdetailserviceimpl处理认证权限

调用登录接口生成token

携带token调用hello接口

修改HelloController对应hello方法权限

@PreAuthorize("hasAuthority(tsest)")

携带有效token也是无法响应页面的,由于该接口权限tsest从缓存redis查询并没有,故而无法显示

4.3.3 从数据库查询权限信息

// UserDetailsServiceImpl
List<String> authoritiesList = menuMapper.selectPermsByUserId(user.getId());

5 自定义失败处理

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

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

如果是认证过程中出现的异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint 对象的方法去进行异常处理。

如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler 对象的方法去进行异常处理。

所以如果我们需要自定义异常处理,我们只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可。 自定义认证失败实现类

/**
 * 认证失败处理器
 **/
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
          
   
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
          
   
        // 处理异常
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), authException.getMessage());
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }
}

自定义认证失败处理器

/**
 * 授权失败处理器
 **/
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
          
   
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
          
   
        // 处理异常
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), accessDeniedException.getMessage());
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }
}

springsecurity配置信息

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
          
   

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    // 创建BCryptPasswordEncoder注入容器
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
          
   
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
          
   
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
          
   
        httpSecurity
                // CSRF禁用,因为不使用session
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 把token校验过滤器添加到过滤器链中
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

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

        return httpSecurity.build();
    }
}
http://localhost:8080/user/login

请求体

{
          
   
    "userName": "",
    "password": "1234"
}

响应体

{
          
   
    "code": 401,
    "msg": "用户名或者密码错误"
}

修改

@GetMapping("/hello") @PreAuthorize("hasAuthority(system:dept:list1)") public String hello() { return "hello"; }
http://localhost:8080/hello

响应体

{
          
   
    "code": 403,
    "msg": "不允许访问"
}

6 跨域

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

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

所以我们就要处理一下,让前端能进行跨域请求。 先对SpringBoot配置,运行跨域请求

package com.geekmice.springsecuritytokendemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * springboot跨域配置
 */
@Configuration
public 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);
    }
}

开启SpringSecurity的跨域访问

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

package com.geekmice.springsecuritytokendemo.config;

import com.geekmice.springsecuritytokendemo.filter.JwtAuthenticationTokenFilter;
import com.geekmice.springsecuritytokendemo.handler.AccessDeniedHandlerImpl;
import com.geekmice.springsecuritytokendemo.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.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
          
   

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
          
   
        return new BCryptPasswordEncoder();
    }

    public static void main(String[] args) {
          
   
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 加密方法 encode
        String encodeFirst = bCryptPasswordEncoder.encode("1234");
        String encodeSecond = bCryptPasswordEncoder.encode("1234");
        System.out.println(encodeFirst); // $2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC
        System.out.println(encodeSecond); //  $2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm
        // 判断明文与密文是否一致 matches
        boolean flag = bCryptPasswordEncoder.matches("1234", "$2a$10$bNcTcfJvmnlJAyzJ85mJCuQnui7WKtb4jadvQSNCjeZXCFv29VvWm");
        boolean flagSecond = bCryptPasswordEncoder.matches("1234", "$2a$10$DNb4zOC0P3xyGCrF6KxfhuJW82S/QYrzjWkEylQj/bRaLBehmh4OC");
        System.out.println(flag); // true
        System.out.println(flagSecond); // true
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
          
   
        // 关闭csrf
        http.csrf().disable()
                // 不通过session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 登录接口允许匿名访问,不需要登录
                .antMatchers("/user/login").anonymous()
                // 登不登陆都可以访问
                .antMatchers("/hello").permitAll()
                // 除了上面的所有请求均需要鉴权认证
                .anyRequest().authenticated()
        ;
        // 把token校验过滤器添加到过滤器链,在UsernamePasswordAuthenticationFilter前面
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

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

        // 允许跨域
        http.cors();
    }

    /**
     * @Description 暴露AuthenticationManager
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
          
   
        return super.authenticationManagerBean();
    }


}
经验分享 程序员 微信小程序 职场和发展