Spring Boot整合Apache Shiro实现安全认证与权限控制

📅 2026/7/21 8:26:15
Spring Boot整合Apache Shiro实现安全认证与权限控制
1. Apache Shiro与Spring Boot整合概述在Java应用开发中安全机制是不可或缺的核心组件。Apache Shiro作为轻量级安全框架相比Spring Security具有更简单的API和更低的认知成本。我曾在多个生产项目中采用Shiro进行权限控制其简洁的设计哲学让开发团队能够快速上手。Shiro的核心优势在于它将安全操作抽象为四个基础概念认证Authentication、授权Authorization、会话管理Session Management和加密Cryptography。这种清晰的边界划分使得开发者可以按需使用各个模块。例如在最近的一个电商项目中我们仅用两天就完成了从零到生产的权限系统搭建。2. 环境准备与基础配置2.1 依赖管理在Spring Boot项目中引入Shiro需要添加以下核心依赖dependency groupIdorg.apache.shiro/groupId artifactIdshiro-spring-boot-starter/artifactId version1.9.0/version /dependency建议使用starter包而非单独的shiro-core和shiro-spring因为它会自动处理许多配置项。我曾遇到过手动配置时Bean初始化顺序问题starter包完美解决了这个痛点。2.2 基础配置类创建ShiroConfig配置类时需要注意几个关键点Configuration public class ShiroConfig { Bean public SessionManager sessionManager() { DefaultWebSessionManager manager new DefaultWebSessionManager(); manager.setSessionIdUrlRewritingEnabled(false); // 关闭URL重写 return manager; } Bean public DefaultWebSecurityManager securityManager(Realm realm) { DefaultWebSecurityManager manager new DefaultWebSecurityManager(); manager.setRealm(realm); manager.setRememberMeManager(null); // 禁用rememberMe return manager; } }特别提示在生产环境中务必关闭sessionIdUrlRewriting否则可能导致会话固定攻击。我在一次安全审计中就发现过因此导致的中危漏洞。3. 认证与授权实现3.1 自定义Realm开发Realm是Shiro与业务系统对接的桥梁需要重点实现两个方法public class CustomRealm extends AuthorizingRealm { Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { String username (String) token.getPrincipal(); User user userService.findByUsername(username); if(user null) { throw new UnknownAccountException(用户不存在); } return new SimpleAuthenticationInfo( user, // 身份主体 user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName() ); } Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { User user (User) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo info new SimpleAuthorizationInfo(); // 添加角色和权限 info.setRoles(roleService.getRoleCodes(user.getId())); info.setStringPermissions(permissionService.getPermissions(user.getId())); return info; } }3.2 密码加密策略Shiro推荐使用HashedCredentialsMatcher进行密码比对Bean public HashedCredentialsMatcher credentialsMatcher() { HashedCredentialsMatcher matcher new HashedCredentialsMatcher(); matcher.setHashAlgorithmName(SHA-256); matcher.setHashIterations(1000); matcher.setStoredCredentialsHexEncoded(false); return matcher; }在用户注册时需要采用相同的算法加密public String encryptPassword(String password, String salt) { return new SimpleHash( SHA-256, password, ByteSource.Util.bytes(salt), 1000 ).toBase64(); }4. 权限控制实战4.1 URL拦截配置ShiroFilterFactoryBean是配置请求拦截的核心Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { ShiroFilterFactoryBean factory new ShiroFilterFactoryBean(); factory.setSecurityManager(securityManager); MapString, String filterMap new LinkedHashMap(); // 静态资源放行 filterMap.put(/static/**, anon); // 登录接口放行 filterMap.put(/api/login, anon); // 管理员路径需要admin角色 filterMap.put(/admin/**, roles[admin]); // 其他请求需要认证 filterMap.put(/**, authc); factory.setFilterChainDefinitionMap(filterMap); return factory; }4.2 注解式权限控制除了URL配置还可以使用注解RequiresPermissions(user:create) PostMapping(/users) public Result createUser(RequestBody User user) { // 创建用户逻辑 }支持的注解包括RequiresAuthenticationRequiresUserRequiresGuestRequiresRolesRequiresPermissions5. 会话管理与缓存5.1 分布式会话方案在集群环境中需要配置分布式会话Bean public SessionDAO sessionDAO() { RedisSessionDAO dao new RedisSessionDAO(); dao.setRedisManager(redisManager()); dao.setSessionIdGenerator(new JavaUuidSessionIdGenerator()); dao.setExpire(1800); // 30分钟过期 return dao; }5.2 缓存配置权限信息通常需要缓存Bean public CacheManager cacheManager() { RedisCacheManager cacheManager new RedisCacheManager(); cacheManager.setRedisManager(redisManager()); cacheManager.setKeyPrefix(shiro:cache:); return cacheManager; }6. 常见问题排查6.1 认证失败处理在登录控制器中需要处理各种异常PostMapping(/login) public Result login(RequestBody LoginDTO dto) { try { Subject subject SecurityUtils.getSubject(); UsernamePasswordToken token new UsernamePasswordToken( dto.getUsername(), dto.getPassword() ); subject.login(token); return Result.success(); } catch (UnknownAccountException e) { return Result.fail(账号不存在); } catch (IncorrectCredentialsException e) { return Result.fail(密码错误); } catch (LockedAccountException e) { return Result.fail(账号已锁定); } }6.2 权限缓存问题当用户权限变更时需要清除缓存public void clearAuthorizationCache(String username) { SimplePrincipalCollection principals new SimplePrincipalCollection( username, realm.getName() ); AuthorizationCache cache ((AuthorizingRealm)realm).getAuthorizationCache(); if(cache ! null) { cache.remove(principals); } }7. 进阶功能实现7.1 JWT集成对于前后端分离项目可以整合JWTpublic class JwtFilter extends AuthenticatingFilter { Override protected AuthenticationToken createToken( ServletRequest request, ServletResponse response ) { String token getRequestToken(request); return new JwtToken(token); } Override protected boolean onAccessDenied( ServletRequest request, ServletResponse response ) throws Exception { executeLogin(request, response); return true; } }7.2 动态权限控制实现数据库驱动的动态权限Bean public FilterChainDefinitionMap filterChainDefinitionMap() { DynamicFilterChainDefinition chain new DynamicFilterChainDefinition(); chain.addPathDefinition(/**, anon); // 从数据库加载权限配置 ListPermission permissions permissionService.listAll(); permissions.forEach(p - { chain.addPathDefinition( p.getUrl(), perms[ p.getCode() ] ); }); return chain; }8. 性能优化建议8.1 缓存策略优化权限信息建议设置较长的缓存时间如12小时会话信息根据业务需求设置通常30分钟-2小时使用二级缓存内存缓存 Redis缓存8.2 减少授权检查对于频繁访问的接口可以采用白名单机制权限预检查批量权限验证我在处理一个高并发系统时通过预加载用户权限到本地缓存使权限验证速度提升了8倍。