文章目录
十二.SpringSecurity进阶
点击跳转:【 安全框架SpringSecurity入门【详解,附有图文+示例代码】】
一般Web应用的需要进行认证和授权。
- 认证:验证当前访问系统的是不是本系统的用户,并且要确认具体是哪个用户
- 授权:经过认证后判断当前用户是否有权限进行某个操作
认证原理分析:
- Spring Security所解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截,校验每个请求是否能够访问它所期望的资源。根据前边知识的学习,可以通过Filter或AOP等技术来实现;
- Spring Security对Web资源的保护是基于Filter过滤器+AOP实现的,所以我们从Filter来入手,逐步深入Spring Security原理;
- 当初始化Spring Security时,会创建一个名为 SpringSecurityFilterChain的Servlet过滤器,类型为org.springframework.security.web.FilterChainProxy,它实现了javax.servlet.Filter,因此外部的请求会经过该类;
Spring Security过虑器链结构图:
如果前后端分离时 则UsernamePasswordAuthentionFilter
这个过滤器不能直接使用,需要自定义一个
12.1 认证流程
登录校验流程
内置认证过滤器的核心流程:
核心流程梳理如下:
- 认证过滤器(UsernamePasswordAuthentionFilter)接收form表单提交的账户、密码信息,并封装成UsernamePasswordAuthenticationToken认证凭对象;
- 认证过滤器调用认证管理器AuthenticationManager进行认证处理;
- 认证管理器通过调用用户详情服务获取用户详情UserDetails;
- 认证管理器通过密码匹配器PasswordEncoder进行匹配,如果密码一致,则将用户相关的权限信息一并封装到Authentication认证对象中;
- 认证过滤器将Authentication认证过滤器放到认证上下文,方便请求从上下文获取认证信息;
概念速查:
- Authentication接口: 它的实现类,表示当前访问系统的用户,封装了用户相关信息。
- AuthenticationManager接口:定义了认证Authentication的方法
- UserDetailsService接口:加载用户特定数据的核心接口。里面定义了一个根据用户名查询用户信息的方法。
- UserDetails接口:提供核心用户信息。通过UserDetailsService根据用户名获取处理的用户信息要封装成UserDetails对象返回。然后将这些信息封装到Authentication对象中。
12.2简单实现(无权限)
思路分析
登录
-
自定义用户详情类实现
UserDetailsService
在自定的这个类中去数据库查询用户信息
-
自定义登录接口
底层调用ProvideManager的方法进行认证,认证成功生成jwt,存储用户信息(存redis)
在SpringSecurity配置类中队登录接口进行放行
认证校验
-
自定义认证过滤器
获取请求头中的token
解析token获取存入的信息(如userid)
存入安全上下文中
-
SpringSecurity修改配置类,将自定义认证过滤器加到默认认证过滤器前执行。
准备工作
导入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>
mybatis-plus-boot-starter
</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!--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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
-
创建utils工具包,导入工具类
FastJsonRedisSerializer
,JwtUtil
,RedisCache
,ResultJSON
,WebUtils
添加Redis相关配置
Redis使用FastJson序列化
package com.ithz.utils;
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;
/**
* Redis使用FastJson序列化
*
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static
{
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public FastJsonRedisSerializer(Class<T> clazz)
{
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null)
{
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || bytes.length <= 0)
{
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
protected JavaType getJavaType(Class<?> clazz)
{
return TypeFactory.defaultInstance().constructType(clazz);
}
}
RedisCache缓存
package com.ithz.utils;
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);
}
}
Redis配置类
package com.ithz.config;
import com.ithz.utils.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@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;
}
}
响应类
package com.ithz.utils;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ResultJSON<T> {
private Integer code;
private String msg;
private Long count;
private T data;
public ResultJSON(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static ResultJSON successLayui(Long count, Object data){
return new ResultJSON(0,"操作成功",count,data);
}
public static ResultJSON successOrError(boolean bool){
if(bool){
return ResultJSON.success();
}else{
return ResultJSON.error();
}
}
public static ResultJSON success(){
return new ResultJSON(0,"操作成功",null);
}
public static ResultJSON success(Integer code, String msg){
return new ResultJSON(code,msg,null);
}
public static <R> ResultJSON success(R data){
return new ResultJSON(0,"操作成功",data);
}
public static ResultJSON error(){
return new ResultJSON(1,"操作失败",null);
}
public static ResultJSON error(Integer code,String msg){
return new ResultJSON(code,msg,null);
}
public static ResultJSON error(String msg){
return new ResultJSON(1,msg,null);
}
}
JWT工具类
package com.ithz.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;
/**
* JWT工具类
*/
public class JwtUtil {
//有效期为
public static final Long JWT_TTL = 60*60*1000L;// 60 * 60 *1000 一个小时
//设置秘钥明文 盐 对称加密
public static final String JWT_KEY = "hongzhuo";
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, JWT_TTL, 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("wzy") // 签发者
.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 {
// key value
// 登录对象
//8bc20226-77ae-43bb-87c3-3abeb38502f8
//3353d0b6-5f04-4345-b47a-867489955f6e
//System.out.println(UUID.randomUUID());
//JWT 1 hongzhuo
//eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJkYWNhYTcyZGQyNzQ0YjFlYWZiMjczNGUxOWI4ZDJjNyIsInN1YiI6IjEiLCJpc3MiOiJ3enkiLCJpYXQiOjE3MzU1NDI0MDgsImV4cCI6MTczNTU0NjAwOH0.H4kJlGPOGm2vUzQu4eyfzedKWhn3s90LDbredsjlUcs
//eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzFiMGFmNDQ3MTE0ZjJmODY0NDYyZWVhNjc2NDU1YiIsInN1YiI6IjEiLCJpc3MiOiJ3enkiLCJpYXQiOjE3MzU1NDI0MjYsImV4cCI6MTczNTU0NjAyNn0.GLIrF_ZzLrv3BFZdjbe2i2nHC1WLiykRhhNks_QqC7w
String jwt = createJWT("1");
System.out.println(jwt);
//key token eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzFiMGFmNDQ3MTE0ZjJmODY0NDYyZWVhNjc2NDU1YiIsInN1YiI6IjEiLCJpc3MiOiJ3enkiLCJpYXQiOjE3MzU1NDI0MjYsImV4cCI6MTczNTU0NjAyNn0.GLIrF_ZzLrv3BFZdjbe2i2nHC1WLiykRhhNks_QqC7w
// value 登录对象
//解析 token
Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzFiMGFmNDQ3MTE0ZjJmODY0NDYyZWVhNjc2NDU1YiIsInN1YiI6IjEiLCJpc3MiOiJ3enkiLCJpYXQiOjE3MzU1NDI0MjYsImV4cCI6MTczNTU0NjAyNn0.GLIrF_ZzLrv3BFZdjbe2i2nHC1WLiykRhhNks_QqC7w");
System.out.println(claims.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();
}
}
WebUtils工具类
package com.ithz.utils;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
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");
PrintWriter out = response.getWriter();
out.print(string);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
数据库准备
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='用户表'
实体类
package com.ithz.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user")
public class SysUser implements Serializable {
/**
* 主键
*/
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 String createTime;
/**
* 更新人
*/
private Long updateBy;
/**
* 更新时间
*/
private String updateTime;
/**
* 删除标志(0代表未删除,1代表已删除)
*/
private Integer delFlag;
}
yml配置文件
server:
port: 80
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/hz_security?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
username: root
password: sa123456
redis:
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
mapper-locations: classpath:mapper/*xml
实现
【mapper】
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
}
创建一个类实现UserDetailsService接口,重写其中的方法。用户名从数据库中查询用户信息
package com.ithz.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithz.mapper.SysUserMapper;
import com.ithz.pojo.LoginUser;
import com.ithz.pojo.SysUser;
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 SysUserMapper sysUserMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据用户名查询用户信息
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUserName,username);
SysUser sysUser = sysUserMapper.selectOne(wrapper);
//如果查询不到数据就通过抛出异常来给出提示
if(Objects.isNull(sysUser)) {
throw new RuntimeException("用户名或密码错误");
}
//TODO 根据用户查询权限信息 添加到LoginUser中
//封装成UserDetails对象返回
return new LoginUser(sysUser);
}
}
因为UserDetailsService方法的返回值是UserDetails类型,是一个接口,所以需要定义一个类,实现该接口,把用户信息封装在其中。
package com.ithz.pojo;
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;
/**
* @Author:
* @Date:
* @Description: security登录对象
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
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;
}
}
【controller】
@RestController
@RequestMapping("index")
public class IndexController {
@GetMapping("index01")
public String index01(){
return "123....";
}
}
配置密码加密器
实际项目中我们不会把密码明文存储在数据库中。默认使用PasswordEncoder要求数据库中的密码格式为:{id}password 。它会根据id去判断密码的加密方式。但是我们一般不会采用这种方式。所以就需要替换BCryptPasswordEncoder。
我们一般使用SpringSecurity为我们提供的BCryptPasswordEncoder。我们只需要使用把BCryptPasswordEncoder对象注入Spring容器中,SpringSecurity就会使用该PasswordEncoder来进行密码校验。
我们可以定义一个SpringSecurity的配置类,SpringSecurity要求这个配置类要继承WebSecurityConfigurerAdap
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 配置密码加密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
测试:数据库建好,插入用户admin和密码123456,在测试controlle接口时候,输入admin和123456会登录失败,因为配置了密码匹配器,底层将明文的密码123456进行了加密转成了密码。
注意:如果要测试,需要往用户表中写入用户数据,并且如果你想让用户的密码是明文存储,需要在密码前加{noop}
对123456加密存储到数据库
@SpringBootTest
public class SecurityConfigTest {
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 测试密码加密
*/
@Test
public void testEncode() {
String password ="123456";
for (int i = 0; i < 5; i++) {
String encode = passwordEncoder.encode(password);
System.out.println(encode);
// $2a$10$40sUgRP2ngSfeSsgHQCvO.TWZ903fwuFJRxpHoispKn592ImWeEta
// $2a$10$ami/5o1tGcdWweU4OKJRYeAY7LQpFazG/rhO2P50JFtA5M9FIePce
// $2a$10$zout/Nc68b8hL2walZGLgODiTZz77qa.GN7g0LVDYdIhQWChhYh.S
// $2a$10$5MkMXK.r5sC47YVZ.mrTweu0kkQdb.JO7fusSz3xtua10I7ZtqZLu
// $2a$10$eHUiHA.QBrxrA2tGcXc3W.Qu3FGwZ9q0HfamwuWe6.9KglxD9jqe.
}
}
/**
* 匹配明文和密文
*/
@Test
public void testMatch() {
String password ="123456";
String encode = "$2a$10$zout/Nc68b8hL2walZGLgODiTZz77qa.GN7g0LVDYdIhQWChhYh.S";
boolean matches = passwordEncoder.matches(password, encode);
System.out.println(matches);// true
}
}
将123456密码转成密文形式写到数据库
再进行测试http://localhost:80/index/index01
,用户admin,密码123456,可以登录成功
12.3 自定义登录接口
(延续12.2)
在12.2 基础上,自定义登陆接口,然后让SpringSecurity对这个登录接口放行,让用户访问这个接口的时候不用登录也能访问。
在接口实现中通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。
认证成功后需要生成一个jwt令牌,放入响应中,为的是让用户下回请求能通过jwt识别出具体哪个用户,可以把用户信息存入redis,用户id作为key.
【mapper】
@Mapper
public interface SysUserMapper extends BaseMapper<SysUser> {
}
【service】
接口
public interface SysUserService extends IService<SysUser> {
public ResultJSON login(SysUser sysUser);
}
实现
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
@Override
public ResultJSON login(SysUser sysUser) {
// System.out.println("进入登录逻辑service。。。。。。");//成功进入
//创建 Authentication 对象
//sysUser.getUserName(),sysUser.getPassword() 为前端输入的账号密码
UsernamePasswordAuthenticationToken authenticationToken = new
UsernamePasswordAuthenticationToken(
sysUser.getUserName(),sysUser.getPassword());
//认证
Authentication authenticate =
authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
//获取登录对象, 封装到LoginUser中
LoginUser loginUser =
(LoginUser) authenticate.getPrincipal();
// 使用jwt生成token
String token = JwtUtil.createJWT(
loginUser.getSysUser().getId().toString());
//存到redis
redisCache.setCacheObject(
"login:"+loginUser.getSysUser().getId(),
loginUser,1, TimeUnit.HOURS);
//返回token给前端
return ResultJSON.success(token);
}
}
【controller】
@RestController
@RequestMapping("/sysuser")
public class SysUserLoginController {
@Autowired
private SysUserService sysUserService;
/**
* 登录
* @param sysUser
* @return
*/
@PostMapping("/login")
public ResultJSON login(@RequestBody SysUser sysUser){
return sysUserService.login(sysUser);
}
/**
* 获取用户列表
* @return
*/
@GetMapping("/list")
public ResultJSON list(){
return ResultJSON.success();
}
}
【完善SecurityConfig配置类】
对登录接口进行放行,重写authenticationManagerBean
方法
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//关闭csrf
.sessionManagement()// 除上面外的所有请求全部需要鉴权认证
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/sysuser/login").anonymous()// 对于登录接口 允许匿名访问
.anyRequest().authenticated();// 除上面外的所有请求全部需要鉴权认证
/**
* 配置密码加密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
12.4 自定义认证过滤器
(延续12.3)
登录成功后,下次请求需要携带token。但是在12.3中直接访问/sysuser/list接口Spring Security 会拦截住因为它不知道你是否登录,所以我们要自定义认证过滤器,去获取请求头中的token,对token进行解析取出其中的userid,使用userid去redis中获取对应的登录LoginUser对象,获取到对应的登录对象就知道谁登录了,登录成功hou对象再去访问/sysuser/list接口直接放行。
-
需要自定义一个过滤器,这个过滤器会去获取请求头中的token,对token进行解析取出其中的userid。
-
使用userid去redis中获取对应的LoginUser对象。
-
然后封装Authentication对象存入SecurityContextHolder
【创建JwtAuthenticationTokenFilter类】
@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) {
throw new RuntimeException("token非法,token解析失败");
}
//从redis中登录对象
LoginUser loginUser = redisCache.getCacheObject("login:" + userid);
//存入SecurityContextHolder
//TODO 获取权限信息封装到Authentication中
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(loginUser, null, null);
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
//放行
filterChain.doFilter(request, response);
}
}
【完善配置类SecurityConfig】
在过滤器中添加自定义的登录验证过滤器
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//关闭csrf
.sessionManagement()// 除上面外的所有请求全部需要鉴权认证
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/sysuser/login").anonymous()// 对于登录接口 允许匿名访问
.anyRequest().authenticated();// 除上面外的所有请求全部需要鉴权认证
// 在过滤器中添加自定义的登录验证过滤器
http.addFilterBefore(
jwtAuthenticationTokenFilter,
UsernamePasswordAuthenticationFilter.class);
}
/**
* 配置密码加密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
12.5 自定义登出
(延续12.4)
登出1
定义一个登陆接口,然后获取SecurityContextHolder中的认证信息,删除redis中对应的数据即可。
【service】
增加退出接口
public interface SysUserService extends IService<SysUser> {
/**
* 登录
* @param sysUser
* @return
*/
public ResultJSON login(SysUser sysUser);
/**
* 退出
* @return
*/
public ResultJSON logout();
}
实现类,重写退出接口
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
/**
* 自定义登录接口
* @param sysUser
* @return
*/
@Override
public ResultJSON login(SysUser sysUser) {
// System.out.println("进入登录逻辑service。。。。。。");//成功进入
//创建 Authentication 对象
//sysUser.getUserName(),sysUser.getPassword() 为前端输入的账号密码
UsernamePasswordAuthenticationToken authenticationToken = new
UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());
//认证
Authentication authenticate =
authenticationManager.authenticate(authenticationToken);
if(Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
//获取登录对象, 封装到LoginUser中
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
// 使用jwt生成token
String token = JwtUtil.createJWT(
loginUser.getSysUser().getId().toString());
//存到redis
redisCache.setCacheObject("login:"+loginUser.getSysUser().getId(),
loginUser,1, TimeUnit.HOURS);
//返回token给前端
return ResultJSON.success(token);
}
/**
* 自定退出
* @return
*/
@Override
public ResultJSON logout() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 获取当前登录的用户
LoginUser loginUser = (LoginUser)authentication.getPrincipal();
//获取当前登录的用户id
long userId = loginUser.getSysUser().getId();
// 根据id删除redis中的用户信息
redisCache.deleteObject("login:"+userId);
return ResultJSON.success(200,"退出成功");
}
}
【controller】
增加退出请求
@RestController
@RequestMapping("/sysuser")
public class SysUserLoginController {
@Autowired
private SysUserService sysUserService;
/**
* 登录
* @param sysUser
* @return
*/
@PostMapping("/login")
public ResultJSON login(@RequestBody SysUser sysUser){
return sysUserService.login(sysUser);
}
/**
* 登出
* @return
*/
@GetMapping("/logout")
public ResultJSON logout(){
return sysUserService.logout();
}
/**
* 获取用户列表
* @return
*/
@GetMapping("/list")
public ResultJSON list(){
return ResultJSON.success();
}
}
登出2
【实现LogoutSuccessHandler接口退出】
package com.ithz.security;
import com.alibaba.fastjson.JSON;
import com.ithz.utils.JwtUtil;
import com.ithz.utils.RedisCache;
import com.ithz.utils.ResultJSON;
import com.ithz.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
@Autowired
private RedisCache redisCache;
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
String userid = "";
try {
userid = JwtUtil.parseJWT(request.getHeader("token")).getSubject();
} catch (Exception e) {
throw new RuntimeException(e);
}
redisCache.deleteObject("login:"+userid);
String json = JSON.toJSONString(ResultJSON.success(200,"退出成功"));
WebUtils.renderString(response,json);
}
}
修改SecurityConfig配置类
package com.ithz.config;
import com.ithz.security.AccessDeniedHandlerImpl;
import com.ithz.security.JwtAuthenticationTokenFilter;
import com.ithz.security.LogoutSuccessHandlerImpl;
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.EnableWebSecurity;
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) //开启SpringSecurity注解支持
@EnableWebSecurity // 开启SpringSecurity的功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandlerImpl;
@Autowired
private AccessDeniedHandlerImpl accessDeniedHandlerImpl;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//关闭csrf
.sessionManagement()// 除上面外的所有请求全部需要鉴权认证
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/user/login").anonymous()// 对于登录接口 允许匿名访问
.anyRequest().authenticated();// 除上面外的所有请求全部需要鉴权认证
// 在过滤器中添加自定义的登录验证过滤器
http.addFilterBefore(
jwtAuthenticationTokenFilter,
UsernamePasswordAuthenticationFilter.class);
//安全退出
http.logout().logoutSuccessHandler(logoutSuccessHandlerImpl);
/**
* 配置密码加密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
【测试】
12.6 授权
12.6.1基本流程
12.6.2简单授权实现
(延续12.5)
SpringSecurity为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式。我们可以使用注解去指定访问对应的资源所需的权限。
在SpringSecurity配置类或者启动类中开启SpringSecurity注解支持
//开启SpringSecurity注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity // 开启SpringSecurity的功能
开启SpringSecurity注解功能后,可以使用注解
限制访问资源所需权限
@RestController
@RequestMapping("/sysuser")
public class SysUserLoginController {
@Autowired
private SysUserService sysUserService;
/**
* 登录
* @param sysUser
* @return
*/
@PostMapping("/login")
public ResultJSON login(@RequestBody SysUser sysUser){
return sysUserService.login(sysUser);
}
/**
* 登出
* @return
*/
@GetMapping("/logout")
public ResultJSON logout(){
return sysUserService.logout();
}
/**
* 获取用户列表
* @return
*/
@GetMapping("/list")
@PreAuthorize("hasAuthority('USER1')")
public ResultJSON list(){
return ResultJSON.success();
}
}
@RestController
@RequestMapping("/bill")
public class BillController {
@GetMapping("/list")
@PreAuthorize("hasAuthority('USER2')")
public ResultJSON list(){
return ResultJSON.success();
}
}
封装权限信息
在写UserDetailsServiceImpl的时候说过,在查询出用户后还要获取对应的权限信息,封装到UserDetails中返回。
先直接把权限信息写死封装到UserDetails中进行测试。
之前定义了UserDetails的实现类LoginUser,想要让其能封装权限信息就要对其进行修改。
【修改LoginUser类】
package com.ithz.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
@Data
@ToString
@NoArgsConstructor
// @AllArgsConstructor
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;
}
/**
* 存储SpringSecurity所需要的权限信息的集合
*
* @JSONField(serialize = false)作用:
* 当对象转换为JSON格式时,该字段不会被包含在生成的JSON字符串中。
*/
@JSONField(serialize = false)
private List<GrantedAuthority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if(authorities!=null){
return authorities;
}
//把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
// authorities = permissions.stream().
// map(SimpleGrantedAuthority::new)
// .collect(Collectors.toList());
authorities=AuthorityUtils
.commaSeparatedStringToAuthorityList(
String.join(",", permissions));
return authorities;
// 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;
}
}
LoginUser修改完后我们就可以在UserDetailsServiceImpl中去把权限信息封装到LoginUser中了。我们写死权限进行测试,后面我们再从数据库中查询权限信息。
package com.ithz.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithz.mapper.SysUserMapper;
import com.ithz.pojo.LoginUser;
import com.ithz.pojo.SysUser;
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.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 自定义用户详情服务实现类
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private SysUserMapper sysUserMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据用户名查询用户信息
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUserName,username);
SysUser sysUser = sysUserMapper.selectOne(wrapper);
//如果查询不到数据就通过抛出异常来给出提示
if(Objects.isNull(sysUser)) {
throw new RuntimeException("用户名或密码错误");
}
//TODO 根据用户查询权限信息 添加到LoginUser中
//权限信息集合,从数据库中根据用户id,获得角色编码
//这里先将权限写死,方便测试
List<String> permissions = new ArrayList<>();
permissions.add("USER1");
// permissions.add("user2");
//TODO 根据用户查询权限信息 添加到LoginUser中
//封装成UserDetails对象返回
return new LoginUser(sysUser, permissions);
}
}
【JwtAuthenticationTokenFilter中修改如下代码】
package com.ithz.security;
import com.ithz.pojo.LoginUser;
import com.ithz.utils.JwtUtil;
import com.ithz.utils.RedisCache;
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;
/**
* 自定义认证过滤器
*/
@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) {
throw new RuntimeException("token非法,token解析失败");
}
//从redis中登录对象
LoginUser loginUser = redisCache.getCacheObject("login:" + userid);
//存入SecurityContextHolder
//TODO 获取权限信息封装到Authentication中
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
new UsernamePasswordAuthenticationToken(
loginUser,
null,
loginUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
//放行
filterChain.doFilter(request, response);
}
}
测试
12.6.3数据库中获取权限信息
RBAC权限模型
RBAC权限模型(Role-Based Access Control)即:基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。
准备工作
数据库
创建表,并添加数据
【sys_user】之前已经准备好了
【sys_menu】
额外给sys_menu表加个父id(p_id)
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`menu_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '菜单名',
`path` varchar(200) DEFAULT NULL COMMENT '路由地址',
`component` varchar(255) DEFAULT NULL COMMENT '组件路径',
`visible` char(1) DEFAULT '0' COMMENT '菜单状态(0显示 1隐藏)',
`status` char(1) DEFAULT '0' COMMENT '菜单状态(0正常 1停用)',
`perms` varchar(100) DEFAULT NULL COMMENT '权限标识',
`icon` varchar(100) DEFAULT '#' COMMENT '菜单图标',
`create_by` bigint(20) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` bigint(20) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`del_flag` int(11) DEFAULT '0' COMMENT '是否删除(0未删除 1已删除)',
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COMMENT='菜单表';
【sys_role】
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`role_key` varchar(100) DEFAULT NULL COMMENT '角色权限字符串',
`status` char(1) DEFAULT '0' COMMENT '角色状态(0正常 1停用)',
`del_flag` int(1) DEFAULT '0' COMMENT 'del_flag',
`create_by` bigint(200) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_by` bigint(200) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`remark` varchar(500) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='角色表';
【sys_role_menu】
DROP TABLE IF EXISTS `sys_role_menu`;
CREATE TABLE `sys_role_menu` (
`role_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '角色ID',
`menu_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '菜单id',
PRIMARY KEY (`role_id`,`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
【sys_user_role】
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`user_id` bigint(200) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`role_id` bigint(200) NOT NULL DEFAULT '0' COMMENT '角色id',
PRIMARY KEY (`user_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
实体类
package com.ithz.pojo;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @Author:
* @Date:
* @Description: 菜单表(权限表)
*/
@TableName(value="sys_menu")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Menu {
@TableId
private Long id;
/**
* 菜单名
*/
private String menuName;
/**
* 路由地址
*/
private String path;
/**
* 组件路径
*/
private String component;
/**
* 菜单状态(0显示 1隐藏)
*/
private String visible;
/**
* 菜单状态(0正常 1停用)
*/
private String status;
/**
* 权限标识
*/
private String perms;
/**
* 菜单图标
*/
private String icon;
private Long createBy;
private Date createTime;
private Long updateBy;
private Date updateTime;
/**
* 是否删除(0未删除 1已删除)
*/
private Integer delFlag;
/**
* 备注
*/
private String remark;
}
权限不足接口
package com.ithz.security;
import com.alibaba.fastjson.JSON;
import com.ithz.utils.ResultJSON;
import com.ithz.utils.WebUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 权限不足提示接口
*/
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
String json = JSON.toJSONString(ResultJSON.success(403,"权限不足"));
WebUtils.renderString(response,json);
}
}
在SecurityConfig配置类中加入 权限不足接口
package com.ithz.config;
import com.ithz.security.AccessDeniedHandlerImpl;
import com.ithz.security.JwtAuthenticationTokenFilter;
import com.ithz.security.LogoutSuccessHandlerImpl;
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.EnableWebSecurity;
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) //开启SpringSecurity注解支持
@EnableWebSecurity // 开启SpringSecurity的功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
private LogoutSuccessHandlerImpl logoutSuccessHandlerImpl;
@Autowired
private AccessDeniedHandlerImpl accessDeniedHandlerImpl;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//关闭csrf
.sessionManagement()// 除上面外的所有请求全部需要鉴权认证
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/user/login").anonymous()// 对于登录接口 允许匿名访问
.anyRequest().authenticated();// 除上面外的所有请求全部需要鉴权认证
// http.csrf().disable();//关闭csrf
// //配置不通过session获得context 禁用form表单
// http.sessionManagement()// 除上面外的所有请求全部需要鉴权认证
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// .and()
// .authorizeRequests()
// .antMatchers("/sysuser/login").anonymous()// 对于登录接口 允许匿名访问
// .anyRequest().authenticated();// 除上面外的所有请求全部需要鉴权认证
// 在过滤器中添加自定义的登录验证过滤器
http.addFilterBefore(
jwtAuthenticationTokenFilter,
UsernamePasswordAuthenticationFilter.class);
//安全退出
http.logout().logoutSuccessHandler(logoutSuccessHandlerImpl);
//权限不足
http.exceptionHandling().accessDeniedHandler(accessDeniedHandlerImpl);
}
/**
* 配置密码加密方式
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
代码实现
【mapper】
package com.ithz.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ithz.pojo.Menu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface SysMenuMapper extends BaseMapper<Menu> {
/**
* 根据用户ID 查询角色权限集合
* @param id
* @return
*/
@Select("SELECT \n" +
"\tDISTINCT m.`perms`\n" +
"FROM\n" +
"\tsys_user_role ur\n" +
"\tLEFT JOIN `sys_role` r ON ur.`role_id` = r.`id`\n" +
"\tLEFT JOIN `sys_role_menu` rm ON ur.`role_id` = rm.`role_id`\n" +
"\tLEFT JOIN `sys_menu` m ON m.`id` = rm.`menu_id`\n" +
"WHERE\n" +
"\tuser_id = #{id}\n" +
"\tAND r.`status` = 0\n" +
"\tAND m.`status` = 0\n" +
"\tand m.`perms` is not null")
public abstract List<String> findMenuRoleById(Long id);
}
然后我们可以在UserDetailsServiceImpl中去调用该mapper的方法查询权限信息封装到LoginUser对象中即可。
package com.ithz.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithz.mapper.SysMenuMapper;
import com.ithz.mapper.SysUserMapper;
import com.ithz.pojo.LoginUser;
import com.ithz.pojo.SysUser;
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.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 自定义用户详情服务实现类
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysMenuMapper sysMenuMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//根据用户名查询用户信息
LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SysUser::getUserName,username);
SysUser sysUser = sysUserMapper.selectOne(wrapper);
//如果查询不到数据就通过抛出异常来给出提示
if(Objects.isNull(sysUser)) {
throw new RuntimeException("用户名或密码错误");
}
//TODO 根据用户查询权限信息 添加到LoginUser中
//权限信息集合,从数据库中根据用户id,获得角色编码
// List<String> permissions = new ArrayList<>();
// permissions.add("USER1");
// // permissions.add("user2");
List<String> permissions = sysMenuMapper.findMenuRoleById(sysUser.getId());
//TODO 根据用户查询权限信息 添加到LoginUser中
//封装成UserDetails对象返回
return new LoginUser(sysUser, permissions);
}
}
测试
登录后可以看到权限信息存到redis中
手动删除,测试权限不足的情况
然后退出后再登录访问用户新增接口
标签:return,进阶,示例,springframework,SpringSecurity,org,import,public,String From: https://blog.csdn.net/weixin_54555405/article/details/144944545