一、项目说明
项目环境:jdk1.7+tomcat7+idea2018+maven+shiro1.3.2
源代码github地址:https://github.com/tmAlj/shiro/tree/master/ssms
实现目标:通过使用部分权限注解,实现相应的效果,达到对shiro的权限注解的使用与理解
综合实例:基于shiro的按钮级别的权限管理系统
二、权限注解
注:shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用aop的功能来进行判断。shiro提供了spring aop集成,用于权限注解的解析和验证
(1)@RequiresAuthentication :表示当前Subject已经通过login 进行了身份验证;即Subject. isAuthenticated()返回true
(2)@RequiresUse:表示当前Subject已经身份验证或者通过记住我登录的
(3)@RequiresGuest :表示当前Subject没有身份验证或通过记住我登录过,即是游客身份
(4)@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND)
(5)@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR) :表示当前Subject需要权限user:a或user:b
三、使用示例
注:注解可以用在service或controller中,本节所有示例基于shiro学习笔记十一:shiro中的jsp标签
(1)配置aop注解
注:在spring-shiro-config.xml配置
<!-- 配置shiro中bean生命周期管理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- AOP式方法级权限检查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
(2)开启注解
注:需要在spring-mvc-config.xml配置aop注解的启动,如果在spring或shiro配置中配置,可能后面使用注解的时候无效
<!-- 开启shiro中aop注解 -->
<aop:config proxy-target-class="true"></aop:config>
(3)配置controller
//注入service
@Autowired
ShiroServiceImpl ssi;
/**
* 权限注解测试
* @return
*/
@RequestMapping("/test")
public String note(){
ssi.test();
return "redirect:/welcom.jsp";
}
(4)配置service
package com.wsd.service.impl;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Service;
/**
* Created by tm on 2018/8/19.
* 权限注解测试service
*/
@Service("ShiroServiceImpl")
public class ShiroServiceImpl {
//只有admin角色才能访问该方法,其他角色访问将会抛出异常
@RequiresRoles({"admin"})
public void test(){
System.out.println("xxxxxxxxxxxxxxxxxxxx");
}
}
(5)welcom.jsp页面添加测试链接
四、测试示例
注:示例是通过在service方法上使用@RequiresRoles({"admin"})注解,当用户为admin/123456时,会调用该方法;当用户为user/123456时在调用该方法时会抛出异常
(1)登录/login.jsp
(2)登录成功/welcom.jsp
(3)非admin用户登录
(4)admin用户登录