权限验证框架Shiro学习(二)

本文介绍Shiro权限管理系统中三种授权方式:使用PermissionAuthorizationFilter过滤器、在方法上使用Shiro注解以及使用JSP标签。文章详细解释了每种方式的具体实现,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


shrio授权,验证主体subject对当前操作有没有该权限

授权,有三种方式

第一种:通过使用PermissionAuthorizationFilter过滤拦截,方式就是通过application-shiro.xml中的<filterChainDefinitions>中配置个perms

例如,对goods/query的访问需要[good:query]权限

<filterChainDefinitions>

    goods/query/** = perms[goods:query]

</filterChainDefinitions>

上一节也说了,这个是通过PermissionAuthorizationFilter进行过滤,这样配置好了,怎么拦截呢,同样是在我们的realm中,realm中有两个方法,一个是认证,认证就是根据token的userCode查询用户基本信息,密码,菜单,等信息构造一个SimpleAuthenticationInfo的bean返回,剩下的就是shiro去验证了

还有一个方式是授权,该方法主要是返回改用户所拥有的权限,剩下的就是shrio根据上面xml的配置,看请求资源的权限是否返回的权限列表中,

// 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal();

        List<String> permissions = new ArrayList<String>();
        List<UserMenuPermission> permissionList = userInfo.getPermissions();
        if (permissionList != null && permissionList.size() > 0) {
            for (UserMenuPermission permission : permissionList) {
                permissions.add(permission.getUrl());
            }
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

这样就完成了授权验证,如果没有该权限,则跳转到我们xml定义的UnAnthorizationUrl的页面,但是这样授权认证有个缺陷就是每个请求都要配置,这样比较麻烦,而且每次都要访问数据库,就是都要访问上面代码,而该代码又访问数据库,这样对性能肯定也会有影响,所以下面的配置方式,要解决上面的配置麻烦,性能问题。


第二种:在方法上加注解

shrio注解方式是比较推荐的,而且配置也很简单

首先在我们的mvc配置文件中

<!-- 开启aop对类代理 -->
    <aop:config proxy-target-class="true"></aop:config>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager" />
    </bean>

<aop:config proxy-target-class="true"> 开启spring mvc对类的代理,因为我们要在@Controller层的方法上加shrio的注解,@Controller是类,不是接口,所以要开启

<bean>的配置是把shrio的管理也交给spring管理

实例代码:

@RequestMapping("/query")
    @RequiresPermissions("item:query")  // shiro注解
    public String queryGoods(HttpServletRequest request) {

        List<Goods> goodsList = new ArrayList<Goods>();
        for (int i=0; i<5; i++) {
            Goods goods = new Goods(i+1, "商品" + i, 10D, new Date(), "详情");
            goodsList.add(goods);
        }

        request.setAttribute("itemsList", goodsList);

        return "itemsList";
    }


我们只要在该方法上加上个注解,上面的方法表示该方法需要item:query的权限,很简单方便,功能等同于上面那种方式在xml里要加,但很简单

下面我们要解决下缓存的问题:

缓存是为了解决我们在验证授权的时候,频繁访问数据库的情况

配置:

1、新建shiro-cache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <diskStore path="E:\develop\ehcache" />
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

2、在application-shiro.xml中增加配置

 <!-- shiro缓存配置 -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:spring/application-shiro-ehcache.xml" />
    </bean>

3、在securityManager引入cacheManager bean
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm" />
        <property name="cacheManager" ref="cacheManager" />
    </bean>

这样就第一次访问某个请求的时候才会到自定义realm的授权方法,同时还要注意缓存的清除

4、清除缓存

在自定义的realm重写

public void clearCached() {
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principalCollection);
    }
在需要清除调用的时候清除缓存,一般是在权限修改后调用


第三种 jsp标签

在jsp页面引入标签库

<%@ tagliburi="http://shiro.apache.org/tags" prefix="shiro" %>


标签名称    标签条件(均是显示标签内容)
<shiro:authenticated>    登录之后
<shiro:notAuthenticated>    不在登录状态时
<shiro:guest>    用户在没有RememberMe时
<shiro:user>    用户在RememberMe时
<shiro:hasAnyRoles name="abc,123" >    在有abc或者123角色时
<shiro:hasRole name="abc">    拥有角色abc
<shiro:lacksRole name="abc">    没有角色abc
<shiro:hasPermission name="abc">    拥有权限资源abc
<shiro:lacksPermission name="abc">    没有abc权限资源
<shiro:principal>    显示用户身份名称
 <shiro:principal property="username"/>     显示用户身份中的属性值

这个类似我们的EL表达式上的逻辑判断,比如

<shiro:hasPermisson name="item:query">

   拥有权限

</shiro:hasPermission>


日常开发中可以用注解 加 标签的方式结合使用













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值