SpringSecurity(三)SpringBoot集成SpringSecurity实现认证授权
-
SpringSecurity(一)基础知识
-
SpringSecurity(二)用户认证定制和用户授权
一、简介
前面学习了Spring Security
认证与授权原理,在之前的文章也学习了JWT
,现在就通过一个SpringBoot
项目集成Spring Security、JWT、Redis、Mybaties-Plus
实现常见的用户认证与授权。
要实现的目标:
- 自定义登录接口,实现基于
SpringSecurity
的认证,并生成JWT
,将信息存入Redis
中。 - 定义
JWT
认证过滤器,获取Token
,并解析Token
,从Redis
中获取用户信息。 - 自定义权限校验方法,从数据库查询权限信息,通过校验注解进行校验。
二、实现
新建SpringBoot
项目SpringBootSpringSecurityApplication
1、添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.duan</groupId>
<artifactId>SpringBoot-SpringSecurity</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.50</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<!--mybatisPlus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<!--redis依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--jwt依赖-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
</project>
2、添加Redis相关配置
config
包下添加RedisConfig
配置类
package com.duan.config;
import com.duan.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 db
* @version 1.0
* @description RedisConfig
* @since 2024/9/22
*/
@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;
}
}
utils
包下添加FastJsonRedisSerializer
package com.duan.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
/**
* Redis使用FastJson序列化
* @author db
* @version 1.0
* @description FastJsonRedisSerializer
* @since 2024/9/22
*/
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);
}
}
config
包下添加Redis
缓存相关信息
package com.duan.config;
/**
* @author db
* @version 1.0
* @description RedisCache
* @since 2024/9/22
*/
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);
}
}
3、添加响应类ResponseResult
package com.duan.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* @author db
* @version 1.0
* @description ResponseResult
* @since 2023/7/12
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> implements Serializable {
private static final long serialVersionUID = 2233637474601103587L;
// 接口响应状态码
private Integer code;
// 接口响应信息
private String msg;
// 接口响应的数据
private T data;
public ResponseResult() {
this.code = AppHttpCodeEnum.SUCCESS.getCode();
this.msg = AppHttpCodeEnum.SUCCESS.getMsg();
}
public ResponseResult(Integer code, T data) {
this.code = code;
this.data = data;
}
public ResponseResult(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public ResponseResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseResult errorResult(int code, String msg) {
ResponseResult result = new ResponseResult();
return result.error(code, msg);
}
public static ResponseResult okResult() {
ResponseResult result = new ResponseResult();
return result;
}
public static ResponseResult okResult(int code, String msg) {
ResponseResult result = new ResponseResult();
return result.ok(code, null, msg);
}
public static ResponseResult okResult(Object data) {
ResponseResult result = setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getMsg());
if (data != null) {
result.setData(data);
}
return result;
}
public static ResponseResult errorResult(AppHttpCodeEnum enums) {
return setAppHttpCodeEnum(enums, enums.getMsg());
}
public static ResponseResult errorResult(AppHttpCodeEnum enums, String msg) {
return setAppHttpCodeEnum(enums, msg);
}
public static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums) {
return okResult(enums.getCode(), enums.getMsg());
}
private static ResponseResult setAppHttpCodeEnum(AppHttpCodeEnum enums, String msg) {
return okResult(enums.getCode(), msg);
}
public ResponseResult<?> error(Integer code, String msg) {
this.code = code;
this.msg = msg;
return this;
}
public ResponseResult<?> ok(Integer code, T data) {
this.code = code;
this.data = data;
return this;
}
public ResponseResult<?> ok(Integer code, T data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
return this;
}
public ResponseResult<?> ok(T data) {
this.data = data;
return this;
}
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;
}
}
utils
包下添加枚举信息AppHttpCodeEnum
package com.duan.utils;
/**
* @author db
* @version 1.0
* @description AppHttpCodeEnum
* @since 2023/7/12
*/
public enum AppHttpCodeEnum {
// 成功
SUCCESS(200,"操作成功"),
// 失败
ERROR(500,"操作失败"),
// 登录
NEED_LOGIN(401,"需要登录后操作"),
NO_OPERATOR_AUTH(403,"无权限操作"),
SYSTEM_ERROR(500,"出现错误"),
USERNAME_EXIST(501,"用户名已存在"),
PHONENUMBER_EXIST(502,"手机号已存在"),
EMAIL_EXIST(503, "邮箱已存在"),
REQUIRE_USERNAME(504, "必需填写用户名"),
LOGIN_ERROR(505,"用户名或密码错误");
int code;
String msg;
AppHttpCodeEnum(int code, String errorMessage){
this.code = code;
this.msg = errorMessage;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
4、添加JWT
工具类
utils
包下添加JwtUtil
package com.duan.utils;
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;
/**
* @author db
* @version 1.0
* @description JwtUtil
* @since 2022/11/23
*/
public class JwtUtil {
//有效期为
public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文
public static final String JWT_KEY = "cxyxkk";
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("cxykk") // 签发者
.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();
}
/**
* 生成加密后的秘钥 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();
}
}
5、用户实体类
pojo
包下新建SysUser
实体类
package com.duan.pojo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* 用户表(SysUser)表实体类
*
* @author db
* @since 2024-09-22 19:49:48
*/
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user")
public class SysUser implements Serializable {
private static final long serialVersionUID = 767991252105621231L;
//主键
@TableId
private Long id;
@ApiModelProperty("用户名")
@TableField("user_name")
private String userName;
@ApiModelProperty("密码")
@TableField("password")
private String password;
@ApiModelProperty("创建日期")
@TableField(value = "create_time",fill = FieldFill.INSERT)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty("更新日期")
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}
我们从前面文章所知,我们需要从数据库校验用户,所以需要先新建数据库、数据表等信息。先创建一个用户表,建表语句如下所示:
CREATE TABLE `sys_user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名',
`password` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '密码',
`create_time` DATETIME DEFAULT NULL COMMENT '创建时间',
`update_time` DATETIME DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='用户表'
配置文件配置数据库信息。
spring:
datasource:
url: jdbc:mysql://localhost:3306/security_test?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
定义Mapper
接口在Mapper
包中新建SysUserMapper
package com.duan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.duan.pojo.SysUser;
import org.apache.ibatis.annotations.Mapper;
/**
* 用户表(SysUser)表数据库访问层
*
* @author db
* @since 2024-09-22 19:49:45
*/
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
}
在启动类上配置包扫描路径。
package com.duan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author db
* @version 1.0
* @description SpringBootSpringSecurityApplication
* @since 2024/9/22
*/
@SpringBootApplication
@MapperScan("com.duan.mapper")
public class SpringBootSpringSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSpringSecurityApplication.class);
}
}
在测试类上测试MP
是否能正常使用。
package com.duan;
import com.duan.mapper.SysMenuMapper;
import com.duan.mapper.SysUserMapper;
import com.duan.pojo.SysUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* @author db
* @version 1.0
* @description TestSecurity
* @since 2024/9/22
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestSecurity {
@Resource
private SysUserMapper sysUserMapper;
@Test
public void test(){
SysUser sysUser = sysUserMapper.selectById(2);
System.out.println(sysUser.toString());
List<SysUser> sysUsers = sysUserMapper.selectList(null);
System.out.println(sysUsers.toString());
}
}
@RunWith(SpringRunner.class)
是 JUnit
测试框架中的一个注解,用于指定测试运行器(Test Runner)
。它的主要作用是将 Spring
的测试支持集成到 JUnit
测试中,使得在运行 JUnit
测试时,Spring
的上下文可以被正确地加载和配置。
6、从数据库查询用户信息
创建一个类实现UserDetailsService
,重写其中方法。
package com.duan.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.duan.exception.SpringSecurityException;
import com.duan.mapper.SysMenuMapper;
import com.duan.mapper.SysUserMapper;
import com.duan.pojo.LoginUser;
import com.duan.pojo.SysUser;
import com.duan.utils.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author db
* @version 1.0
* @description UserDetailsServiceImpl
* @since 2024/9/22
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
public UserDetails loadUserByUsername(String username) {
LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysUser::getUserName,username);
SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
if(sysUser == null){
throw new SpringSecurityException(AppHttpCodeEnum.LOGIN_ERROR.getCode(),AppHttpCodeEnum.LOGIN_ERROR.getMsg());
}
//根据用户查询权限信息 添加到LoginUser中
//封装成UserDetails对象返回
return new LoginUser(sysUser);
}
}
UserDetailsService
方法的返回值是UserDetails
类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。
package com.duan.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author db
* @version 1.0
* @description LoginUser
* @since 2024/9/22
*/
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
private SysUser sysUser;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return sysUser.getPassword();
}
@Override
public String getUsername() {
return sysUser.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;
}
}
7、登录接口
需要自定义登陆接口,然后让Spring Security
对这个接口放行,让用户访问这个接口的时候不用登录也能访问。
在接口中我们通过AuthenticationManager
的authenticate
方法来进行用户认证,所以需要在SecurityConfig
中配置把AuthenticationManager
注入容器。
认证成功的话要生成一个jwt
,放入响应中返回。并且为了让用户下回请求时能通过jwt
识别出具体的是哪个用户,我们需要把用户信息存入redis
,可以把用户id
作为key
。
package com.duan.controller;
import com.duan.pojo.SysUser;
import com.duan.service.LoginService;
import com.duan.utils.ResponseResult;
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;
/**
* @author db
* @version 1.0
* @description LoginController
* @since 2024/9/24
*/
@RestController
public class LoginController {
@Autowired
private LoginService loginService;
@PostMapping("/user/login")
public ResponseResult login(@RequestBody SysUser sysUser){
String jwt = loginService.login(sysUser);
HashMap<String, Object> map = new HashMap<>();
map.put("token",jwt);
return ResponseResult.okResult(map);
}
}
package com.duan.service.impl;
import com.duan.config.RedisCache;
import com.duan.pojo.LoginUser;
import com.duan.pojo.SysUser;
import com.duan.service.LoginService;
import com.duan.utils.JwtUtil;
import com.duan.utils.ResponseResult;
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.Objects;
/**
* @author db
* @version 1.0
* @description LoginServiceImpl
* @since 2024/9/24
*/
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Override
public String login(SysUser sysUser) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
//使用userId生成token
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
String userId = loginUser.getSysUser().getId().toString();
String jwt = JwtUtil.createJWT(userId);
//authenticate存入redis
redisCache.setCacheObject("login:"+userId,loginUser);
return jwt;
}
}
package com.duan.service;
import com.duan.pojo.SysUser;
/**
* @author db
* @version 1.0
* @description LoginServcie
* @since 2024/9/24
*/
public interface LoginService {
String login(SysUser sysUser);
}
在config
包下新建SecurityConfig
配置类
package com.duan.config;
import com.duan.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;
/**
* @author db
* @version 1.0
* @description SecurityConfig
* @since 2024/9/22
*/
@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();
}
}
其中项目中我们一般是密码加密存储,一般使用SpringSecurity
为我们提供的BCryptPasswordEncoder
,所以配置文件中把BCryptPasswordEncoder
对象注入Spring
容器中,SpringSecurity
就会使用该PasswordEncoder
来进行密码校验。
8、认证过滤器
需要自定义一个过滤器,这个过滤器会获取请求头中的Token
,对Token
进行解析获得userid
。
使用userid
去redis
中获取对应的LoginUser
对象。
然后封装Authentication
对象存入SecurityContextHolder
。
filter
包下新建JwtAuthenticationTokenFilter
package com.duan.filter;
import com.duan.config.RedisCache;
import com.duan.pojo.LoginUser;
import com.duan.utils.JwtUtil;
import io.jsonwebtoken.Claims;
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.util.StringUtils;
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;
/**
* @author db
* @version 1.0
* @description JwtAuthenticationTokenFilter
* @since 2024/9/24
*/
@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.hasText(token)) {
//放行
filterChain.doFilter(request, response);
return;
}
//解析token
String userid;
try {
Claims claims = JwtUtil.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
// 获取权限信息封装到Authentication中
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginUser,null,null);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//放行
filterChain.doFilter(request, response);
}
}
在 SecurityConfig
中把Token
校验过滤器添加到过滤器链中。
package com.duan.config;
import com.duan.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;
/**
* @author db
* @version 1.0
* @description SecurityConfig
* @since 2024/9/22
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@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();
//把token校验过滤器添加到过滤器链中
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter .class);
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
9、退出登录
定义一个退出登录接口,然后获取SecurityContextHolder
中的认证信息,删除redis
中对应的数据即可。
package com.duan.controller;
import com.duan.config.RedisCache;
import com.duan.pojo.LoginUser;
import com.duan.pojo.SysUser;
import com.duan.service.LoginService;
import com.duan.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author db
* @version 1.0
* @description LoginController
* @since 2024/9/24
*/
@RestController
public class LoginController {
@Autowired
private LoginService loginService;
@Autowired
private RedisCache redisCache;
@PostMapping("/user/login")
public ResponseResult login(@RequestBody SysUser sysUser){
String jwt = loginService.login(sysUser);
HashMap<String, Object> map = new HashMap<>();
map.put("token",jwt);
return ResponseResult.okResult(map);
}
@PostMapping("/user/logout")
public ResponseResult logout(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
Long id = loginUser.getSysUser().getId();
redisCache.deleteObject("login:"+id);
return ResponseResult.okResult();
}
}
10、测试登录接口,获得token
访问http://localhost:8088/user/login
11、授权
基本流程:
在SpringSecurity
中,会使用默认的FilterSecurityInterceptor
来进行权限校验。在FilterSecurityInterceptor
中会从SecurityContextHolder
获取其中的Authentication
,然后获取其中的权限信息。当前用户是否拥有访问当前资源所需的权限。
所以我们在项目中只需要把当前登录用户的权限信息也存入Authentication
。然后设置我们的资源所需要的权限即可。
SpringSecurity
为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式。我们可以使用注解去指定访问对应的资源所需的权限。但是要使用它我们需要先开启相关配置。在SecurityConfig
配置类上开启相关配置。
@EnableGlobalMethodSecurity(prePostEnabled = true)
然后就可以使用对应的注解。@PreAuthorize
package com.duan.controller;
import com.duan.pojo.SysUser;
import com.duan.service.SysUserService;
import com.duan.utils.ResponseResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 用户表(SysUser)表控制层
*
* @author db
* @since 2024-09-22 19:49:44
*/
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@GetMapping("/getSysUserList")
@PreAuthorize("hasAnyAuthority('system:user:list')")
public ResponseResult getSysUserList(){
List<SysUser> sysUserList = sysUserService.getSysUserList();
return ResponseResult.okResult(sysUserList);
}
}
封装权限信息前面在写UserDetailsServiceImpl
的时候说过,在查询出用户后还要获取对应的权限信息,封装到UserDetails
中返回。之前定义了UserDetails
的实现类LoginUser
,想要让其能封装权限信息就要对其进行修改。
package com.duan.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author db
* @version 1.0
* @description LoginUser
* @since 2024/9/22
*/
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
private SysUser sysUser;
private List<String> permissions;
public LoginUser(SysUser sysUser, List<String> permissions) {
this.sysUser = sysUser;
this.permissions = permissions;
}
@JSONField(serialize = false)
private List<GrantedAuthority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if(authorities !=null){
return authorities;
}
authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
return authorities;
}
@Override
public String getPassword() {
return sysUser.getPassword();
}
@Override
public String getUsername() {
return sysUser.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;
}
}
从数据库中查询权限信息。
# 新建数据表
CREATE TABLE `sys_role` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128) DEFAULT NULL,
`create_time` DATETIME DEFAULT NULL,
`update_time` DATETIME DEFAULT NULL,
`remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';
CREATE TABLE `sys_menu` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`menu_name` VARCHAR(64) NOT NULL DEFAULT 'NULL' COMMENT '菜单名',
`component` VARCHAR(255) DEFAULT NULL COMMENT '组件路径',
`perms` VARCHAR(100) DEFAULT NULL COMMENT '权限标识',
`create_time` DATETIME DEFAULT NULL,
`update_time` DATETIME DEFAULT NULL,
`remark` VARCHAR(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';
CREATE TABLE `sys_role_menu` (
`role_id` BIGINT(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`menu_id` BIGINT(200) NOT NULL DEFAULT '0' COMMENT '菜单id',
PRIMARY KEY (`role_id`,`menu_id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
CREATE TABLE `sys_user_role` (
`user_id` BIGINT(200) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`role_id` BIGINT(200) NOT NULL DEFAULT '0' COMMENT '角色id',
PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
新建对应的实体类。
package com.duan.pojo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* (SysUserRole)表实体类
*
* @author db
* @since 2024-10-04 22:13:31
*/
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_user_role")
public class SysUserRole implements Serializable {
private static final long serialVersionUID = 767991252105621233L;
//用户id
@TableField("user_id")
private Long userId;
//角色id
@TableField("role_id")
private Long roleId;
}
package com.duan.pojo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* 菜单表(SysMenu)表实体类
*
* @author db
* @since 2024-10-04 22:18:43
*/
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_menu")
public class SysMenu implements Serializable {
private static final long serialVersionUID = 767991252105621234L;
@TableId
private Long id;
//菜单名
@TableField("menu_name")
private String menuName;
//组件路径
private String component;
//权限标识
private String perms;
//备注
private String remark;
@ApiModelProperty("创建日期")
@TableField(value = "create_time",fill = FieldFill.INSERT)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty("更新日期")
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}
package com.duan.pojo;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
/**
* 角色表(SysRole)表实体类
*
* @author db
* @since 2024-10-04 21:49:53
*/
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_role")
public class SysRole implements Serializable {
private static final long serialVersionUID = 767991252105621232L;
@TableId
private Long id;
private String name;
//备注
private String remark;
@ApiModelProperty("创建日期")
@TableField(value = "update_time",fill = FieldFill.INSERT)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty("更新日期")
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}
package com.duan.pojo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* (SysRoleMenu)表实体类
*
* @author db
* @since 2024-10-04 22:26:47
*/
@SuppressWarnings("serial")
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("sys_role_menu")
public class SysRoleMenu implements Serializable {
private static final long serialVersionUID = 767991252105621235L;
//角色ID
@TableField("role_id")
private Long roleId;
//菜单id
@TableField("menu_id")
private Long menuId;
}
先定义个mapper
,其中提供一个方法可以根据userid
查询权限信息。
package com.duan.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.duan.pojo.SysMenu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 菜单表(SysMenu)表数据库访问层
*
* @author db
* @since 2024-10-04 22:18:42
*/
@Mapper
public interface SysMenuMapper extends BaseMapper<SysMenu> {
List<String> selectPermsByUserId(@Param("userId") Long userId);
}
尤其是自定义方法,所以需要创建对应的mapper
文件,定义对应的sql
语句。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.duan.mapper.SysMenuMapper">
<select id="selectPermsByUserId" resultType="java.lang.String">
SELECT
DISTINCT m.`perms`
FROM
sys_user_role ur
LEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`
LEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`
LEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`
WHERE
user_id = #{userId}
</select>
</mapper>
然后可以在UserDetailsServiceImpl
中去调用该mapper
的方法查询权限信息封装到LoginUser
对象中即可。
package com.duan.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.duan.exception.SpringSecurityException;
import com.duan.mapper.SysMenuMapper;
import com.duan.mapper.SysUserMapper;
import com.duan.pojo.LoginUser;
import com.duan.pojo.SysUser;
import com.duan.utils.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author db
* @version 1.0
* @description UserDetailsServiceImpl
* @since 2024/9/22
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
public UserDetails loadUserByUsername(String username) {
LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysUser::getUserName,username);
SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
if(sysUser == null){
throw new SpringSecurityException(AppHttpCodeEnum.LOGIN_ERROR.getCode(),AppHttpCodeEnum.LOGIN_ERROR.getMsg());
}
//根据用户查询权限信息 添加到LoginUser中
List<String> perms = sysMenuMapper.selectPermsByUserId(sysUser.getId());
//封装成UserDetails对象返回
return new LoginUser(sysUser,perms);
}
}
修改自定义的认证过滤器,将获得的用户权限封装Authentication
对象,存入SecurityContextHolder
。
package com.duan.filter;
import com.duan.config.RedisCache;
import com.duan.pojo.LoginUser;
import com.duan.utils.JwtUtil;
import io.jsonwebtoken.Claims;
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.util.StringUtils;
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;
/**
* @author db
* @version 1.0
* @description JwtAuthenticationTokenFilter
* @since 2024/9/24
*/
@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.hasText(token)) {
//放行
filterChain.doFilter(request, response);
return;
}
//解析token
String userid;
try {
Claims claims = JwtUtil.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
// 获取权限信息封装到Authentication中
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//放行
filterChain.doFilter(request, response);
}
}
12、跨域
浏览器出于安全的考虑,使用 XMLHttpRequest
对象发起 HTTP
请求时必须遵守同源策略,否则就是跨域的HTTP
请求,默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。
前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。所以我们就要处理一下,让前端能进行跨域请求。
①先对SpringBoot
配置,运行跨域请求。
package com.duan.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author db
* @version 1.0
* @description CorsConfig
* @since 2024/10/8
*/
@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.duan.config;
import com.duan.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;
/**
* @author db
* @version 1.0
* @description SecurityConfig
* @since 2024/9/22
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@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();
//把token校验过滤器添加到过滤器链中
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter .class);
//允许跨域
http.cors();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
13、授权测试
先使用用户程序员康康登录,获得token
,然后去访问用户列表接口,请求值携带token
值,可以看到能访问到该接口。
再使用用户张三登录,获得token
,然后去访问用户列表接口,请求值携带token
值,可以看到不能访问该接口,没有权限。
14、自定义权限校验方法
我们还可以自定义权限校验方法,在PreAuthorize
注解中使用我们的方法。
package com.duan.filter;
import com.duan.pojo.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author db
* @version 1.0
* @description PermissionService
* @since 2024/11/6
*/
@Component("ss")
public class PermissionService {
public boolean hasAuthority(String authority){
//获取当前用户的权限
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
List<String> permissions = loginUser.getPermissions();
//判断用户权限集合中是否存在authority
return permissions.contains(authority);
}
}
在SPEL
表达式中使用 @ss
相当于获取容器中Bean
的名字ss
的对象。然后再调用这个对象的hasAuthority
方法。
package com.duan.controller;
import com.duan.pojo.SysUser;
import com.duan.service.SysUserService;
import com.duan.utils.ResponseResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 用户表(SysUser)表控制层
*
* @author db
* @since 2024-09-22 19:49:44
*/
@RestController
@RequestMapping("sysUser")
public class SysUserController {
/**
* 服务对象
*/
@Resource
private SysUserService sysUserService;
@GetMapping("/getSysUserList")
@PreAuthorize("hasAnyAuthority('system:user:list')")
public ResponseResult getSysUserList(){
List<SysUser> sysUserList = sysUserService.getSysUserList();
return ResponseResult.okResult(sysUserList);
}
@GetMapping("/getSysUserListSS")
@PreAuthorize("@ss.hasAuthority('system:user:list')")
public ResponseResult getSysUserListSS(){
List<SysUser> sysUserList = sysUserService.getSysUserList();
return ResponseResult.okResult(sysUserList);
}
}
使用用户张三登录,获得token
,然后去访问用户列表接口getSysUserListSS
,请求值携带token
值,可以看到不能访问该接口,没有权限。
代码地址: https://gitee.com/duan138/practice-code/tree/dev/SpringBoot-SpringSecurity
三、总结
前面几篇文章学习Spring security
认证和授权理论知识,本文通过实际案例去整合Spring Security
进行认证和授权,进行数据库级别的RBAC
鉴权操作,引入JWT
和Redis
进行Token
认证,本案例可以在实际项目中使用。
改变你能改变的,接受你不能改变的,关注公众号:程序员康康,一起成长,共同进步。