Shiro想必大家都知道了,之前的文章我也有提過,是目前使用率要比spring security都要多的一個權限框架,本身spring自己都在用shiro,之前的文章有興趣可以去扒一下
最近正好用到shiro,簡單聊聊幾個小tips吧
<!-- 對靜態資源設置匿名訪問,即可以未登錄狀態下訪問 --> /images/** = anon /js/** = anon /styles/** = anon /css/** = anon /page/getOrders.action = perms[order:query] /page/editOrderItemCounts.action = perms[order:edit]
在對資源訪問的時候需要對url進行權限配置,在spring-shiro.xml中需要配置大量的上述代碼,這樣做可以,但是十分的冗余,而且也不利於后期維護,就像當初的hibernate一樣,有很多的hbm文件,所以后來很多人都是用了注解形式,當然了,shiro也支持注解,這樣的話會非常方便,程序員再開發代碼的時候就可以完善相應的權限
在springmvc.xml中進行配置
<!-- 開啟aop,對類代理 --> <aop:config proxy-target-class="true"></aop:config> <!-- 開啟shiro注解支持 --> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean>
這樣就可以在代碼中使用注解了,需要注意的是,注解可以再controller, service 以及dao層使用,但是建議再controller中攔截,因為入口只有一個,而其他兩層的方法是可以公用的
@RequiresPermissions("order:query")
另外jsp上可以這樣使用:
<shiro:hasPermission name="order:edit"> <a href="<%=request.getContextPath() %>/page/editOrderItemCounts">修改商品</a> </shiro:hasPermission> <br/><br/> <shiro:hasPermission name="order:query">當前用戶有查詢訂單權限</shiro:hasPermission> <shiro:lacksPermission name="order:add">當前用戶沒有下單權限</shiro:lacksPermission>
OK,這樣整個權限的控制就沒有問題了,直接控制到資源,而不是角色。
<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"/> 顯示用戶身份中的屬性值
最后再附上一張最基本的5張數據庫權限表