描述在 MyBatis-Plus 插件中结合 Shiro 实现“只能看本部门数据”的方案。

解读

国内项目普遍要求“数据权限”比“功能权限”更细:用户登录后能点菜单不代表能看全表。面试官问这道题,想验证三点:

  1. 你是否理解 Shiro 只解决“谁能执行”,不解决“能看到哪些行”;
  2. 能否把 Shiro 的“当前用户”无缝透传到 MyBatis-Plus 的 SQL 改写层;
  3. 方案是否对业务代码零侵入、支持多租户+部门树等国内常见场景。

答“在 SQL 里手动加 dept_id=?”只能得 30 分;答“用 MyBatis-Plus 数据权限插件 + Shiro 会话”才能拿满分。

知识点

  1. Shiro 会话存储:SecurityUtils.getSubject().getPrincipal() 拿到用户对象,含 deptId。
  2. MyBatis-Plus 数据权限插件(DataPermissionInterceptor):在 SQL 执行前改写 WHERE,支持自定义规则。
  3. ThreadLocal 透传:登录成功后把 deptId 放进 Shiro 的 Session,再通过 TransmittableThreadLocal 传到 MyBatis 线程。
  4. 部门树递归:国内公司部门常是多级树,需支持“本部门及子部门”或“本部门及所有下级”两种策略,用 MPTT 或 closure 表缓存。
  5. 缓存一致性:部门调整时清 Shiro 授权缓存,避免用户换部门后依旧看到旧数据。
  6. 性能优化:数据权限条件提前拼成 dept_id IN (…) 一次性绑定,防止 N+1;结合 MyBatis-Plus 的 TenantLineInnerInterceptor 实现多租户+部门双维度隔离。

答案

  1. 登录成功后,Shiro Realm 把用户 ID、deptId、roleIds 封装成 UserProfile 放入 SimpleAuthenticationInfo 的 principals,同时写进 Shiro Session:

    session.setAttribute("deptId", user.getDeptId());
    
  2. 定义数据权限规则枚举:

    public enum DataScope {
        DEPT_ONLY,    // 仅本部门
        DEPT_AND_SUB, // 本部门及子部门
        ALL           // 全部,管理员用
    }
    
  3. 实现 MyBatis-Plus DataPermissionHandler:

    @Component
    public class DeptDataPermissionHandler implements DataPermissionHandler {
        @Override
        public Expression getSqlSegment(Expression where, String mappedStatementId) {
            // 从 TTL 拿到当前用户
            UserProfile user = UserContextHolder.get();
            if (user == null || user.isAdmin()) return where;
    
            Long deptId = user.getDeptId();
            DataScope scope = user.getDataScope(); // 从角色表带出来
    
            Set<Long> deptIds = scope == DataScope.DEPT_ONLY
                ? Collections.singleton(deptId)
                : deptService.listSubDeptIds(deptId); // 递归子部门,带缓存
    
            // 构造 dept_id IN (…)
            InExpression in = new InExpression(new Column("dept_id"),
                deptIds.stream().map(LongValue::new).collect(Collectors.toList()));
            return where == null ? in : new AndExpression(where, in);
        }
    }
    
  4. 注册插件:

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(DataPermissionHandler handler) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new DataPermissionInterceptor(handler));
        return interceptor;
    }
    
  5. 线程透传:借助 Alibaba TTL 线程池,把 Shiro Session 的 deptId 在 Web 层→Service 层→MyBatis 层全程传递,保证异步线程也能取到。

  6. 清缓存:部门调整后发 MQ 消息,消费者调用 shiroCacheManager.getCache("authorizationCache").clear(),强制用户重新授权并刷新 deptId。

至此,业务 Mapper 代码零改动,所有带 dept_id 的表自动追加“只能看本部门”条件,满足国内等保与数据合规要求。

拓展思考

  1. 跨部门协作:国内常见“项目负责人”能看到项目维度数据,但项目成员来自多部门。可扩展一张 project_member(user_id, project_id) 关系表,在 DataPermissionHandler 里先判断是否有项目权限,再决定是否追加 dept 条件,实现“维度权限优先于部门权限”。
  2. 数据脱敏:结合 Shiro 的自定义注解 @RequiresDataMask,在返回 VO 阶段对手机号、身份证做脱敏,实现“权限+脱敏”双保险。
  3. 分布式场景:Spring Cloud 下把 UserProfile 放进 JWT payload,网关解析后写入请求头,下游服务通过 HandlerMethodArgumentResolver 注入,保证 Feign 调用也能取到 deptId,避免“内部调用绕过权限”。
  4. 性能极限:单表 5000W 行时,dept_id 加索引仍可能回表过多;可引入分区表按 dept_id 做 RANGE 分区,或把热点部门数据冗余到部门级 Redis 缓存,实现亚毫秒级响应。