shiro实现动态权限管理

用到shiro框架实现权限控制时,根据实际要求,权限在数据库增删改后都要把权限过滤链变化实时更新到服务器中。

1、配置文件里配置的filterchains都是静态的,但实际开发中更多的是从数据库中动态的获取filterchains。

我们都知道ShiroFilterFactoryBean中的setFilterChainDefinitions()是读取配置文件里默认的filterchains,所以我们的思路是重写这个方法,才能达到我们想要的目的:

package com.xiyinli.web.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xiyinli.model.CoreUser;
import com.xiyinli.model.RolesPermissions;
import com.xiyinli.service.CoreUserService;
import com.xiyinli.service.RolesPermissionsService;
import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/8/14 0014.
 */
public class ShiroPermissionFactory extends ShiroFilterFactoryBean {
    /**记录配置中的过滤链*/
    public static String definition = "";
    @Autowired
    private RolesPermissionsService rolesPermissionsService;

    /**
     * 初始化设置过滤链
     */
    @Override
    public void setFilterChainDefinitions(String definitions) {
//        String token =  manageUserService.getAdminToken(0);

        //可从数据库读取后,添加至过滤链,参考此处已注释的代码
        definition = definitions;//记录配置的静态过滤链
//        List<Permission> permissions = permissService.findAll();

        List<RolesPermissions> rolesPermissions = rolesPermissionsService.selectList(new EntityWrapper<>());
        Set<String> urls = new LinkedHashSet<>();
        for (RolesPermissions rolesPermission : rolesPermissions) {
            urls.add(rolesPermission.getUrl());
        }

        Map<String,String> otherChains = new HashMap<>();
        for (String url : urls) {
            StringBuilder roleOrFilters = new StringBuilder();
            for (int i = 0; i < rolesPermissions.size(); i++) {
                if (Objects.equals(url, rolesPermissions.get(i).getUrl())) {
                    if (i == 0) {
                        roleOrFilters.append(rolesPermissions.get(i).getRolesName());
                    }else{
                        roleOrFilters.append(",").append(rolesPermissions.get(i).getRolesName());
                    }
                }
            }
            String rolesStr = roleOrFilters.toString();
            if (!"".equals(rolesStr)) {
                otherChains.put(url, "roleOrFilter["+rolesStr+"]"); //  /discover/newstag  authc,roles[user,admin]
            }
        }
        //加载配置默认的过滤链
        Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
        if (CollectionUtils.isEmpty(section)) {
            section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        }
        //加上数据库中过滤链
        section.putAll(otherChains);
        section.put("/**", "anon");
        setFilterChainDefinitionMap(section);
    }
}

 

这里定义的一个静态属性definition,作用是记录下配置文件中的filterchains,这个属性在等下更新权限的时候会用到。

配置文件 spring-shiro.xml 如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 缓存管理器(自带) -->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/>

    <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
    <!--<bean id="codeRealm" class="com.xiyinli.web.shiro.CodeRealm"/>-->

    <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
    <bean id="passwordRealm" class="com.xiyinli.web.shiro.PasswordRealm"/>

    <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->
    <bean id="adminPasswordRealm" class="com.xiyinli.web.shiro.AdminPasswordRealm"/>
    <!-- 踢出用户 -->
    <!--<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO" />-->
    <bean id="sessionDAO" class="com.xiyinli.web.shiro.RedisSessionDao" />
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <property name="sessionDAO" ref="sessionDAO" />
        <property name="globalSessionTimeout" value="-1000"/>
    </bean>
    <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
    <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
    <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realms">
            <list>
                <!--<ref bean="codeRealm" />-->
                <ref bean="passwordRealm" />
                <ref bean="adminPasswordRealm" />
            </list>
        </property>
        <property name="sessionManager" ref="sessionManager" />
        <!-- 使用下面配置的缓存管理器 -->
        <!--<property name="cacheManager" ref="cacheManager"/>-->
    </bean>

    <!--自定义的filter-->
    <bean id="roleOrFilter" class="com.xiyinli.web.shiro.CustomRolesAuthorizationFilter">
    </bean>
    <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
    <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
    <bean id="shiroFilter" class="com.xiyinli.web.shiro.ShiroPermissionFactory">
    <!--<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">-->
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->
        <property name="loginUrl" value="/login.map"/>
        <!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
        <!-- <property name="successUrl" value="/index.html"/> -->
        <!-- 用户访问未对其授权的资源时,所显示的连接 -->
        <!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->
        <property name="unauthorizedUrl" value="/unauthorized.map"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
        <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
        <!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
        <!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
        <property name="filters">
            <util:map>
                <entry key="roleOrFilter" value-ref="roleOrFilter"/>
            </util:map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                # 注意此处配置的路径不需要输入工程名,  / 就包括  http://地址:端口/项目名/
                <!--/api/user/login/** = anon-->
                <!--/api/user/pcLogin/** = anon-->
                <!--/api/user/register/** = anon-->
                <!---->
                <!--/api/user/logout = logout-->
                <!---->
                <!--/assets/**  = anon-->
                <!--/css/**  = anon-->
                <!--/img/**  = anon-->
                <!--/js/**  = anon-->
                <!--/tpl/**  = anon-->

                <!--/login.html  = anon-->
                <!--#/api/admin/** = authc-->
                <!--#/api/coreUser/sendMsmOrEmail/2 = authc-->
                <!--#/api/coreUser/sendMsmOrEmail/3 = authc-->
                <!--#/api/coreUser/sendMsmOrEmail/4 = authc-->
                <!--#/api/coreUser/sendMsmOrEmail/5 = authc-->
                <!--#/api/coreCollection/rmUserCollection = authc-->

                <!--# authc 如果全部放行必须放在最后-->
                /###/@@@/** = authc

            </value>
        </property>
    </bean>

    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->
    <!-- 配置以下两个bean即可实现此功能 -->
    <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run -->
    <!-- 由于本例中并未使用Shiro注解,故注释掉这两个bean(个人觉得将权限通过注解的方式硬编码在程序中,查看起来不是很方便,没必要使用) -->
    <!--
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
      <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
      </bean>
    -->

</beans>

其中:

    <bean id="passwordRealm" class="com.xiyinli.web.shiro.PasswordRealm"/>
    <bean id="adminPasswordRealm" class="com.xiyinli.web.shiro.AdminPasswordRealm"/>
    <bean id="sessionDAO" class="com.xiyinli.web.shiro.RedisSessionDao" />

在此不做详述!

/###/@@@/** = authc

为一个项目接口不存在的路径 权限是authc(需要登录),是为了保证初始过滤链不为空。

<bean id="roleOrFilter" class="com.xiyinli.web.shiro.CustomRolesAuthorizationFilter">

为自定义的filter ,作用是角色权限设置成或者的关系,shiro自带的roles为并且关系,不符合要要求。

package com.xiyinli.web.shiro;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * // AuthorizationFilter抽象类事项了javax.servlet.Filter接口,它是个过滤器。
 * Created by Administrator on 2017/8/15 0015.
 */
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }
        for (String aRolesArray : rolesArray) {
            if (subject.hasRole(aRolesArray)) {
                return true;
            }
        }
        return false;
    }
}

 注(2017.9.13更新):使用如上自定义CustomRolesAuthorizationFilter后实际项目中遇到多角色同时拥有一个接口权限时,会出现多次调用自定义Realm中的doGetAuthorizationInfo方法(原因是是subject.hasRole一次触发一次),严重影响效率。

故自定义CustomRolesAuthorizationFilter做如下更改,修改过后自定义Realm中的doGetAuthorizationInfo方法将不再被调用,角色鉴权在CustomRolesAuthorizationFilter中被执行,其中用到了redis作为缓存:

 

package com.xiyinli.web.shiro;

import com.xiyinli.model.RolesPermissions;
import com.xiyinli.redis.RedisClusterCache;
import com.xiyinli.service.RolesPermissionsService;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * // AuthorizationFilter抽象类事项了javax.servlet.Filter接口,它是个过滤器。
 * Created by Administrator on 2017/8/15 0015.
 */
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {
    private HttpServletRequest request;
    @Autowired
    private RolesPermissionsService rolesPermissionsService;
    @Resource
    private RedisClusterCache redisClusterCache;

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        this.request = (HttpServletRequest) request;
        String localAddr = this.request.getRequestURI();
        PrincipalCollection principals = subject.getPrincipals();
        if (null == principals) {
            return true;
        }
        Session session = subject.getSession();
        Serializable sessionId = session.getId();

        String userName = principals.toString();
        String userName0 = userName.split("==")[0];
        String userName1 = "";

        Object cache = redisClusterCache.getCache(sessionId.toString() + "==" + localAddr + "==" + userName);

        String[] rolesArray = (String[]) mappedValue;
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        List<String> rolesList = Arrays.asList(rolesArray);

        if ("admin-pc".equals(userName0) || "store-pc".equals(userName0)) {
            if (null != cache) {
                Set<String> cache1 = (Set<String>) cache;
                boolean disjoint = Collections.disjoint(cache1, rolesList);
                return !disjoint;
            }
            userName1 = userName.split("==")[1];
        }

        List<RolesPermissions> rolesPermissions;
        if ("admin-pc".equals(userName0)) {
            rolesPermissions = rolesPermissionsService.selectByAuserName(userName1);
        }else if("store-pc".equals(userName0)){
            rolesPermissions = rolesPermissionsService.selectBySuserName(userName1);
        }else{
            return true;
        }
        //当前用户具有的权限
        Set<String> roles = rolesPermissions.stream().map(RolesPermissions::getRolesName).collect(Collectors.toSet());

        redisClusterCache.putCacheWithExpireTime(sessionId.toString() + "==" + localAddr + "==" + userName, roles, 86400); //24小时过期

        boolean disjoint = Collections.disjoint(roles, rolesList);
        if (!disjoint) {
            return true;
        }

        /*for (String aRolesArray : rolesArray) {
            if (subject.hasRole(aRolesArray)) {
                return true;
            }
        }*/
        return false;
    }
}

 

其中我这是多端多角色的,所以有一些截取判断,项目应根据实际做相应修改!

 

2、系统管理员在后台更新权限(增删改)的时候,要保证数据库中的filterchains同步到服务器中。

package com.xiyinli.web.shiro;

import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.Map;

/**
 * Created by Administrator on 2017/8/15 0015.
 */
@Controller
public class FilterChainDefinitionsService {
    @Autowired
    private ShiroPermissionFactory permissFactory;


    public void reloadFilterChains() {
        synchronized (permissFactory) {   //强制同步,控制线程安全
            AbstractShiroFilter shiroFilter = null;

            try {
                shiroFilter = (AbstractShiroFilter) permissFactory.getObject();

                PathMatchingFilterChainResolver resolver = (PathMatchingFilterChainResolver) shiroFilter
                        .getFilterChainResolver();
                // 过滤管理器
                DefaultFilterChainManager manager = (DefaultFilterChainManager) resolver.getFilterChainManager();
                // 清除权限配置
                manager.getFilterChains().clear();
                permissFactory.getFilterChainDefinitionMap().clear();
                // 重新设置权限
                permissFactory.setFilterChainDefinitions(ShiroPermissionFactory.definition);//传入配置中的filterchains

                Map<String, String> chains = permissFactory.getFilterChainDefinitionMap();
                //重新生成过滤链
                if (!CollectionUtils.isEmpty(chains)) {
                    chains.forEach((url, definitionChains) -> {
                        manager.createChain(url, definitionChains.trim().replace(" ", ""));
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

这里要注意线程安全控制,用synchronized关键字。同时,可以看到前面的静态属性definition这里就派上用场了。在接口中修改角色权限时,只需要注入此bean,调用reloadFilterChains()方法即可完成权限的动态更新!



posted @ 2017-08-17 14:33  007少侠  阅读(20818)  评论(4编辑  收藏  举报
友情链接:便宜vps(CN2GIA线路)
站长统计: