这篇文章给大家介绍SpringBoot中怎么利用Shiro动态加载权限,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

临湘网站建设公司创新互联建站,临湘网站设计制作,有大型网站制作公司丰富经验。已为临湘上1000+提供企业网站建设服务。企业网站搭建\成都外贸网站建设要多少钱,请找那个售后服务好的临湘做网站的公司定做!
1、引入相关maven依赖
 1.4.0 3.1.0   org.springframework.boot spring-boot-starter-aop    org.springframework.boot spring-boot-starter-data-redis-reactive    org.apache.shiro shiro-spring ${shiro-spring.version}    org.crazycake shiro-redis ${shiro-redis.version} 
2、自定义Realm
doGetAuthenticationInfo:身份认证 (主要是在登录时的逻辑处理)  doGetAuthorizationInfo:登陆认证成功后的处理 ex: 赋予角色和权限  【 注:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行doGetAuthorizationInfo这个方法去查权限,并放入缓存中 】 -> 因此我们在前端页面分配用户权限时 执行清除shiro缓存的方法即可实现动态分配用户权限
@Slf4jpublic class ShiroRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; @Autowired private MenuMapper menuMapper; @Autowired private RoleMapper roleMapper; @Override public String getName() { return "shiroRealm"; } /** * 赋予角色和权限:用户进行权限验证时 Shiro会去缓存中找,如果查不到数据,会执行这个方法去查权限,并放入缓存中 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); // 获取用户 User user = (User) principalCollection.getPrimaryPrincipal(); Integer userId =user.getId(); // 这里可以进行授权和处理 Set rolesSet = new HashSet<>(); Set permsSet = new HashSet<>(); // 获取当前用户对应的权限(这里根据业务自行查询) List roleList = roleMapper.selectRoleByUserId( userId ); for (Role role:roleList) {  rolesSet.add( role.getCode() );  List
3、Shiro配置类
@Configurationpublic class ShiroConfig { private final String CACHE_KEY = "shiro:cache:"; private final String SESSION_KEY = "shiro:session:"; /** * 默认过期时间30分钟,即在30分钟内不进行操作则清空缓存信息,页面即会提醒重新登录 */ private final int EXPIRE = 1800; /** * Redis配置 */ @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.timeout}") private int timeout;// @Value("${spring.redis.password}")// private String password; /** * 开启Shiro-aop注解支持:使用代理方式所以需要开启代码支持 */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * Shiro基础配置 */ @Bean public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager, ShiroServiceImpl shiroConfig){ ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); // 自定义过滤器 Map filtersMap = new LinkedHashMap<>(); // 定义过滤器名称 【注:map里面key值对于的value要为authc才能使用自定义的过滤器】 filtersMap.put( "zqPerms", new MyPermissionsAuthorizationFilter() ); filtersMap.put( "zqRoles", new MyRolesAuthorizationFilter() ); filtersMap.put( "token", new TokenCheckFilter() ); shiroFilterFactoryBean.setFilters(filtersMap); // 登录的路径: 如果你没有登录则会跳到这个页面中 - 如果没有设置值则会默认跳转到工程根目录下的"/login.jsp"页面 或 "/login" 映射 shiroFilterFactoryBean.setLoginUrl("/api/auth/unLogin"); // 登录成功后跳转的主页面 (这里没用,前端vue控制了跳转)// shiroFilterFactoryBean.setSuccessUrl("/index"); // 设置没有权限时跳转的url shiroFilterFactoryBean.setUnauthorizedUrl("/api/auth/unauth"); shiroFilterFactoryBean.setFilterChainDefinitionMap( shiroConfig.loadFilterChainDefinitionMap() ); return shiroFilterFactoryBean; } /** * 安全管理器 */ @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 自定义session管理 securityManager.setSessionManager(sessionManager()); // 自定义Cache实现缓存管理 securityManager.setCacheManager(cacheManager()); // 自定义Realm验证 securityManager.setRealm(shiroRealm()); return securityManager; } /** * 身份验证器 */ @Bean public ShiroRealm shiroRealm() { ShiroRealm shiroRealm = new ShiroRealm(); shiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return shiroRealm; } /** * 自定义Realm的加密规则 -> 凭证匹配器:将密码校验交给Shiro的SimpleAuthenticationInfo进行处理,在这里做匹配配置 */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher(); // 散列算法:这里使用SHA256算法; shaCredentialsMatcher.setHashAlgorithmName(SHA256Util.HASH_ALGORITHM_NAME); // 散列的次数,比如散列两次,相当于 md5(md5("")); shaCredentialsMatcher.setHashIterations(SHA256Util.HASH_ITERATIONS); return shaCredentialsMatcher; } /** * 配置Redis管理器:使用的是shiro-redis开源插件 */ @Bean public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost(host); redisManager.setPort(port); redisManager.setTimeout(timeout);// redisManager.setPassword(password); return redisManager; } /** * 配置Cache管理器:用于往Redis存储权限和角色标识 (使用的是shiro-redis开源插件) */ @Bean public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); redisCacheManager.setKeyPrefix(CACHE_KEY); // 配置缓存的话要求放在session里面的实体类必须有个id标识 注:这里id为用户表中的主键,否-> 报:User must has getter for field: xx redisCacheManager.setPrincipalIdFieldName("id"); return redisCacheManager; } /** * SessionID生成器 */ @Bean public ShiroSessionIdGenerator sessionIdGenerator(){ return new ShiroSessionIdGenerator(); } /** * 配置RedisSessionDAO (使用的是shiro-redis开源插件) */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); redisSessionDAO.setSessionIdGenerator(sessionIdGenerator()); redisSessionDAO.setKeyPrefix(SESSION_KEY); redisSessionDAO.setExpire(EXPIRE); return redisSessionDAO; } /** * 配置Session管理器 */ @Bean public SessionManager sessionManager() { ShiroSessionManager shiroSessionManager = new ShiroSessionManager(); shiroSessionManager.setSessionDAO(redisSessionDAO()); return shiroSessionManager; }}
三、shiro动态加载权限处理方法
- loadFilterChainDefinitionMap:初始化权限  ex: 在上面Shiro配置类ShiroConfig中的Shiro基础配置shiroFilterFactory方法中我们就需要调用此方法将数据库中配置的所有uri权限全部加载进去,以及放行接口和配置权限过滤器等  【注:过滤器配置顺序不能颠倒,多个过滤器用,分割】  ex: filterChainDefinitionMap.put("/api/system/user/list", "authc,token,zqPerms[user1]")  updatePermission:动态刷新加载数据库中的uri权限 -> 页面在新增uri路径到数据库中,也就是配置新的权限时就可以调用此方法实现动态加载uri权限  updatePermissionByRoleId:shiro动态权限加载 -> 即分配指定用户权限时可调用此方法删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限 
public interface ShiroService { /** * 初始化权限 -> 拿全部权限 * * @param : * @return: java.util.Map */ Map loadFilterChainDefinitionMap(); /** * 在对uri权限进行增删改操作时,需要调用此方法进行动态刷新加载数据库中的uri权限 * * @param shiroFilterFactoryBean * @param roleId * @param isRemoveSession: * @return: void */ void updatePermission(ShiroFilterFactoryBean shiroFilterFactoryBean, Integer roleId, Boolean isRemoveSession); /** * shiro动态权限加载 -> 原理:删除shiro缓存,重新执行doGetAuthorizationInfo方法授权角色和权限 * * @param roleId * @param isRemoveSession: * @return: void */ void updatePermissionByRoleId(Integer roleId, Boolean isRemoveSession);}
@Slf4j@Servicepublic class ShiroServiceImpl implements ShiroService { @Autowired private MenuMapper menuMapper; @Autowired private UserMapper userMapper; @Autowired private RoleMapper roleMapper; @Override public Map loadFilterChainDefinitionMap() { // 权限控制map Map filterChainDefinitionMap = new LinkedHashMap<>(); // 配置过滤:不会被拦截的链接 -> 放行 start ---------------------------------------------------------- // 放行Swagger2页面,需要放行这些 filterChainDefinitionMap.put("/swagger-ui.html","anon"); filterChainDefinitionMap.put("/swagger/**","anon"); filterChainDefinitionMap.put("/webjars/**", "anon"); filterChainDefinitionMap.put("/swagger-resources/**","anon"); filterChainDefinitionMap.put("/v2/**","anon"); filterChainDefinitionMap.put("/static/**", "anon"); // 登陆 filterChainDefinitionMap.put("/api/auth/login/**", "anon"); // 三方登录 filterChainDefinitionMap.put("/api/auth/loginByQQ", "anon"); filterChainDefinitionMap.put("/api/auth/afterlogin.do", "anon"); // 退出 filterChainDefinitionMap.put("/api/auth/logout", "anon"); // 放行未授权接口,重定向使用 filterChainDefinitionMap.put("/api/auth/unauth", "anon"); // token过期接口 filterChainDefinitionMap.put("/api/auth/tokenExpired", "anon"); // 被挤下线 filterChainDefinitionMap.put("/api/auth/downline", "anon"); // 放行 end ---------------------------------------------------------- // 从数据库或缓存中查取出来的url与resources对应则不会被拦截 放行 List
四、shiro中自定义角色、权限过滤器
1、自定义uri权限过滤器 zqPerms
@Slf4jpublic class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String requestUrl = httpRequest.getServletPath(); log.info("请求的url: " + requestUrl); // 检查是否拥有访问权限 Subject subject = this.getSubject(request, response); if (subject.getPrincipal() == null) {  this.saveRequestAndRedirectToLogin(request, response); } else {  // 转换成http的请求和响应  HttpServletRequest req = (HttpServletRequest) request;  HttpServletResponse resp = (HttpServletResponse) response;  // 获取请求头的值  String header = req.getHeader("X-Requested-With");  // ajax 的请求头里有X-Requested-With: XMLHttpRequest 正常请求没有  if (header!=null && "XMLHttpRequest".equals(header)){  resp.setContentType("text/json,charset=UTF-8");  resp.getWriter().print("{\"success\":false,\"msg\":\"没有权限操作!\"}");  }else { //正常请求  String unauthorizedUrl = this.getUnauthorizedUrl();  if (StringUtils.hasText(unauthorizedUrl)) {   WebUtils.issueRedirect(request, response, unauthorizedUrl);  } else {   WebUtils.toHttp(response).sendError(401);  }  } } return false; } }
2、自定义角色权限过滤器 zqRoles
shiro原生的角色过滤器RolesAuthorizationFilter 默认是必须同时满足roles[admin,guest]才有权限,而自定义的zqRoles 只满足其中一个即可访问
ex: zqRoles[admin,guest]
public class MyRolesAuthorizationFilter extends AuthorizationFilter { @Override protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object mappedValue) throws Exception {  Subject subject = getSubject(req, resp);  String[] rolesArray = (String[]) mappedValue;  // 没有角色限制,有权限访问  if (rolesArray == null || rolesArray.length == 0) {   return true;  }  for (int i = 0; i < rolesArray.length; i++) {   //若当前用户是rolesArray中的任何一个,则有权限访问   if (subject.hasRole(rolesArray[i])) {    return true;   }  }  return false; }}
3、自定义token过滤器 token -> 判断token是否过期失效等
@Slf4jpublic class TokenCheckFilter extends UserFilter { /**  * token过期、失效  */ private static final String TOKEN_EXPIRED_URL = "/api/auth/tokenExpired"; /**  * 判断是否拥有权限 true:认证成功 false:认证失败  * mappedValue 访问该url时需要的权限  * subject.isPermitted 判断访问的用户是否拥有mappedValue权限  */ @Override public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {  HttpServletRequest httpRequest = (HttpServletRequest) request;  HttpServletResponse httpResponse = (HttpServletResponse) response;  // 根据请求头拿到token  String token = WebUtils.toHttp(request).getHeader(Constants.REQUEST_HEADER);  log.info("浏览器token:" + token );  User userInfo = ShiroUtils.getUserInfo();  String userToken = userInfo.getToken();  // 检查token是否过期  if ( !token.equals(userToken) ){   return false;  }  return true; } /**  * 认证失败回调的方法: 如果登录实体为null就保存请求和跳转登录页面,否则就跳转无权限配置页面  */ @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {  User userInfo = ShiroUtils.getUserInfo();  // 重定向错误提示处理 - 前后端分离情况下  WebUtils.issueRedirect(request, response, TOKEN_EXPIRED_URL);  return false; }}
五、项目中会用到的一些工具类、常量等
温馨小提示:这里只是部分,详情可参考文章末尾给出的案例demo源码
1、Shiro工具类
public class ShiroUtils { /** 私有构造器 **/ private ShiroUtils(){ } private static RedisSessionDAO redisSessionDAO = SpringUtil.getBean(RedisSessionDAO.class); /**  * 获取当前用户Session  * @Return SysUserEntity 用户信息  */ public static Session getSession() {  return SecurityUtils.getSubject().getSession(); } /**  * 用户登出  */ public static void logout() {  SecurityUtils.getSubject().logout(); } /**  * 获取当前用户信息  * @Return SysUserEntity 用户信息  */ public static User getUserInfo() {  return (User) SecurityUtils.getSubject().getPrincipal(); } /**  * 删除用户缓存信息  * @Param username 用户名称  * @Param isRemoveSession 是否删除Session,删除后用户需重新登录  */ public static void deleteCache(String username, boolean isRemoveSession){  //从缓存中获取Session  Session session = null;  // 获取当前已登录的用户session列表  Collection sessions = redisSessionDAO.getActiveSessions();  User sysUserEntity;  Object attribute = null;  // 遍历Session,找到该用户名称对应的Session  for(Session sessionInfo : sessions){   attribute = sessionInfo.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);   if (attribute == null) {    continue;   }   sysUserEntity = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();   if (sysUserEntity == null) {    continue;   }   if (Objects.equals(sysUserEntity.getUsername(), username)) {    session=sessionInfo;    // 清除该用户以前登录时保存的session,强制退出 -> 单用户登录处理    if (isRemoveSession) {     redisSessionDAO.delete(session);    }   }  }  if (session == null||attribute == null) {   return;  }  //删除session  if (isRemoveSession) {   redisSessionDAO.delete(session);  }  //删除Cache,再访问受限接口时会重新授权  DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();  Authenticator authc = securityManager.getAuthenticator();  ((LogoutAware) authc).onLogout((SimplePrincipalCollection) attribute); } /**  * 从缓存中获取指定用户名的Session  * @param username  */ private static Session getSessionByUsername(String username){  // 获取当前已登录的用户session列表  Collection sessions = redisSessionDAO.getActiveSessions();  User user;  Object attribute;  // 遍历Session,找到该用户名称对应的Session  for(Session session : sessions){   attribute = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);   if (attribute == null) {    continue;   }   user = (User) ((SimplePrincipalCollection) attribute).getPrimaryPrincipal();   if (user == null) {    continue;   }   if (Objects.equals(user.getUsername(), username)) {    return session;   }  }  return null; }}
2、Redis常量类
public interface RedisConstant { /**  * TOKEN前缀  */ String REDIS_PREFIX_LOGIN = "code-generator_token_%s";}
3、Spring上下文工具类
@Componentpublic class SpringUtil implements ApplicationContextAware { private static ApplicationContext context; /**  * Spring在bean初始化后会判断是不是ApplicationContextAware的子类  * 如果该类是,setApplicationContext()方法,会将容器中ApplicationContext作为参数传入进去  */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  context = applicationContext; } /**  * 通过Name返回指定的Bean  */ public static  T getBean(Class beanClass) {  return context.getBean(beanClass); }}
关于SpringBoot中怎么利用Shiro动态加载权限就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
            
            
                                                            
                                                网站栏目:SpringBoot中怎么利用Shiro动态加载权限                                                
                                                文章来源:
http://www.scyingshan.cn/article/jsehsp.html