RBAC权限配置 补充内容

Spring Security整合RBAC与审计日志

一、完整数据库表SQL脚本(MySQL)

-- 1. 用户表
CREATE TABLE `sys_user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(50) NOT NULL COMMENT '用户名(唯一)',
  `password` varchar(100) NOT NULL COMMENT '密码(BCrypt加密)',
  `dept_id` bigint DEFAULT NULL COMMENT '所属部门ID',
  `status` tinyint NOT NULL DEFAULT '1' COMMENT '状态:0-禁用,1-启用',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表';

-- 2. 角色表
CREATE TABLE `sys_role` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `role_code` varchar(50) NOT NULL COMMENT '角色编码(唯一,如ADMIN/ORDER_MANAGER)',
  `role_name` varchar(50) NOT NULL COMMENT '角色名称',
  `data_scope` varchar(20) NOT NULL DEFAULT 'ALL' COMMENT '数据范围:ALL-全部,SELF-本人,DEPT-本部门',
  `desc` varchar(200) DEFAULT '' COMMENT '角色描述',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_role_code` (`role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统角色表';

-- 3. 权限表
CREATE TABLE `sys_permission` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '权限ID',
  `perm_code` varchar(50) NOT NULL COMMENT '权限编码(唯一,如ORDER_VIEW)',
  `resource_type` varchar(20) NOT NULL COMMENT '资源类型:INTERFACE-接口,MENU-菜单,FUNCTION-功能',
  `resource_path` varchar(200) NOT NULL COMMENT '资源路径(如/api/order/list)',
  `request_method` varchar(10) DEFAULT '' COMMENT '请求方式(GET/POST/PUT/DELETE,接口类型必填)',
  `parent_id` bigint DEFAULT '0' COMMENT '父权限ID(0为顶级)',
  `sort` int DEFAULT '0' COMMENT '排序(用于权限展示)',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_perm_code` (`perm_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统权限表';

-- 4. 用户-角色关联表
CREATE TABLE `sys_user_role` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` bigint NOT NULL COMMENT '用户ID',
  `role_id` bigint NOT NULL COMMENT '角色ID',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_role` (`user_id`,`role_id`) COMMENT '避免用户重复绑定同一角色'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户角色关联表';

-- 5. 角色-权限关联表
CREATE TABLE `sys_role_permission` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `role_id` bigint NOT NULL COMMENT '角色ID',
  `perm_id` bigint NOT NULL COMMENT '权限ID',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_role_perm` (`role_id`,`perm_id`) COMMENT '避免角色重复绑定同一权限'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='角色权限关联表';

-- 6. 权限操作日志表(审计用)
CREATE TABLE `sys_perm_oper_log` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '日志ID',
  `oper_user_id` bigint NOT NULL COMMENT '操作人ID',
  `oper_type` varchar(20) NOT NULL COMMENT '操作类型:ROLE_ADD-新增角色,PERM_BIND-绑定权限,USER_ROLE_BIND-用户绑定角色',
  `oper_content` varchar(500) NOT NULL COMMENT '操作内容(如“给角色ID=1绑定权限ID=2,3”)',
  `oper_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
  `ip` varchar(50) DEFAULT '' COMMENT '操作IP',
  PRIMARY KEY (`id`),
  KEY `idx_oper_user_id` (`oper_user_id`),
  KEY `idx_oper_time` (`oper_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='权限操作审计日志表';

二、Spring Security整合RBAC完整代码

1. 核心依赖(pom.xml)

<!-- Spring Security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- JWT(可选,用于前后端分离) -->
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.11.5</version>
    <scope>runtime</scope>
</dependency>
<!-- Redis(缓存用) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Security核心配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Spring Security核心配置
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true) // 启用方法级权限校验
public class SecurityConfig {

    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    @Resource
    private CustomAccessDeniedHandler accessDeniedHandler;
    @Resource
    private CustomAuthenticationEntryPoint authenticationEntryPoint;

    /**
     * 密码加密器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    /**
     * 安全过滤链
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 关闭CSRF(前后端分离不需要)
                .csrf().disable()
                // 关闭Session(基于JWT无状态)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 权限规则配置
                .authorizeHttpRequests()
                // 放行登录/注册接口
                .requestMatchers("/api/auth/login", "/api/auth/register").permitAll()
                // 放行静态资源
                .requestMatchers("/static/**", "/swagger-ui/**", "/v3/api-docs/**").permitAll()
                // 所有请求都需要认证
                .anyRequest().authenticated()
                .and()
                // 异常处理(未登录/无权限)
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint) // 未登录
                .accessDeniedHandler(accessDeniedHandler) // 无权限
                .and()
                // 添加JWT过滤器(在用户名密码过滤器之前)
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

3. JWT认证过滤器(前后端分离必备)

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器:解析token,将用户信息存入SecurityContext
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtProperties jwtProperties; // JWT配置(秘钥、过期时间等)
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1. 获取token
        String token = request.getHeader(jwtProperties.getHeader());
        if (token == null || !token.startsWith(jwtProperties.getPrefix())) {
            filterChain.doFilter(request, response);
            return;
        }
        token = token.replace(jwtProperties.getPrefix(), "").trim();

        // 2. 校验token是否有效(是否在黑名单,如用户登出)
        String blackListKey = "jwt:blacklist:" + token;
        if (redisTemplate.hasKey(blackListKey)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 3. 解析token获取用户名
        Claims claims = Jwts.parser()
                .setSigningKey(jwtProperties.getSecret().getBytes())
                .parseClaimsJws(token)
                .getBody();
        String username = claims.getSubject();

        // 4. 用户名存在且未认证,加载用户信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            // 5. 设置认证信息到SecurityContext
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities()
            );
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }
}

4. 用户详情服务(加载用户权限)

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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 javax.annotation.Resource;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 加载用户详情(用户名+密码+权限)
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserMapper userMapper;
    @Resource
    private UserPermissionService userPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查询用户
        SysUser sysUser = userMapper.selectByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (sysUser.getStatus() == 0) {
            throw new UsernameNotFoundException("用户已禁用");
        }

        // 2. 查询用户权限编码(转换为Spring Security的Authority)
        Set<String> permCodes = userPermissionService.listPermCodesByUserId(sysUser.getId());
        Set<SimpleGrantedAuthority> authorities = permCodes.stream()
                .map(permCode -> new SimpleGrantedAuthority("PERM_" + permCode)) // 前缀区分权限类型
                .collect(Collectors.toSet());

        // 3. 返回UserDetails
        return new User(
                sysUser.getUsername(),
                sysUser.getPassword(),
                authorities
        );
    }
}

5. 自定义异常处理器

import com.alibaba.fastjson2.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

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

/**
 * 无权限异常处理器
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        // 返回标准化结果
        Result<Void> result = Result.fail(HttpStatus.FORBIDDEN.value(), "无权限访问");
        response.getWriter().write(JSON.toJSONString(result));
    }
}

/**
 * 未登录异常处理器
 */
@Component
public class CustomAuthenticationEntryPoint implements org.springframework.security.web.AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, org.springframework.security.core.AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Result<Void> result = Result.fail(HttpStatus.UNAUTHORIZED.value(), "未登录或token已过期");
        response.getWriter().write(JSON.toJSONString(result));
    }
}

6. 方法级权限校验(结合注解)

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

/**
 * 测试接口(Spring Security权限校验)
 */
@RestController
@RequestMapping("/api/test")
public class TestController {

    /**
     * 需ORDER_VIEW权限才能访问
     */
    @GetMapping("/order/list")
    @PreAuthorize("hasAuthority('PERM_ORDER_VIEW')")
    public Result<String> listOrder() {
        return Result.success("订单列表数据");
    }

    /**
     * 需ADMIN角色才能访问
     */
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> admin() {
        return Result.success("管理员专属接口");
    }
}

三、权限审计日志实现示例

1. 自定义操作日志注解

import java.lang.annotation.*;

/**
 * 权限操作日志注解
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PermOperLog {
    /**
     * 操作类型(如ROLE_ADD、PERM_BIND)
     */
    String operType();

    /**
     * 操作内容(支持SpEL表达式,如"给角色ID={#roleId}绑定权限:{#permIds}")
     */
    String operContent();
}

2. 日志记录AOP切面

import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 权限操作日志切面
 */
@Aspect
@Component
public class PermOperLogAspect {

    @Resource
    private SysPermOperLogService permOperLogService;

    private final ExpressionParser parser = new SpelExpressionParser();
    private final LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();

    @Around("@annotation(permOperLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint, PermOperLog permOperLog) throws Throwable {
        // 1. 执行原方法
        Object result = joinPoint.proceed();

        // 2. 解析日志参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Long operUserId = SecurityContextHolder.getCurrentUserId(); // 从上下文获取操作人ID
        String operType = permOperLog.operType();
        String operContent = parseSpel(permOperLog.operContent(), joinPoint);
        String ip = request.getRemoteAddr();

        // 3. 保存日志
        SysPermOperLog log = new SysPermOperLog();
        log.setOperUserId(operUserId);
        log.setOperType(operType);
        log.setOperContent(operContent);
        log.setIp(ip);
        permOperLogService.save(log);

        return result;
    }

    /**
     * 解析SpEL表达式
     */
    private String parseSpel(String spel, ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 获取方法参数名
        String[] paramNames = discoverer.getParameterNames(method);
        // 获取方法参数值
        Object[] args = joinPoint.getArgs();
        // 构建SpEL上下文
        StandardEvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < paramNames.length; i++) {
            context.setVariable(paramNames[i], args[i]);
        }
        // 解析表达式
        return parser.parseExpression(spel).getValue(context, String.class);
    }
}

3. 日志记录使用示例

@RestController
@RequestMapping("/api/admin/role")
public class RoleAdminController {

    @Resource
    private RolePermissionService rolePermissionService;

    /**
     * 给角色绑定权限
     */
    @PostMapping("/{roleId}/bind-perms")
    @RequirePermission("ROLE_MANAGE")
    @PermOperLog(
            operType = "PERM_BIND",
            operContent = "给角色ID={#roleId}绑定权限:{#permIds}"
    )
    public Result<Void> bindPerms(@PathVariable Long roleId, @RequestBody List<Long> permIds) {
        rolePermissionService.bindPerms(roleId, permIds);
        return Result.success();
    }
}

补充总结

  1. SQL脚本:可直接在MySQL执行,包含基础RBAC表+审计日志表,适配绝大多数后端场景;
  2. Spring Security整合:核心是“JWT认证+权限解析+方法级校验”,适配前后端分离架构;
  3. 审计日志:通过AOP+SpEL表达式实现无侵入式日志记录,满足合规审计要求。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红石榴花生油

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值