Shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用AOP的功能来进行判断,如Spring AOP;Shiro提供了Spring AOP集成用于权限注解的解析和验证。
为了测试,此处使用了Spring MVC来测试Shiro注解,当然Shiro注解不仅仅可以在web环境使用,在独立的JavaSE中也是可以用的,此处只是以web为例了。
在spring-mvc.xml配置文件添加Shiro Spring AOP权限注解的支持:
<aop:config proxy-target-class="true"></aop:config>
<bean class="
org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
如上配置用于开启Shiro Spring AOP权限注解的支持;<aop:config proxy-target-class="true">表示代理类。
接着就可以在相应的控制器(AnnotationController)中使用如下方式进行注解:
@RequiresRoles("admin")
@RequestMapping("/hello2")
public String hello2() {
return "success";
}
访问hello2方法的前提是当前用户有admin角色。
当验证失败,其会抛出UnauthorizedException异常,此时可以使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("exception", e);
mv.setViewName("unauthorized");
return mv;
}
如果集成Struts2,需要注意Shiro+Struts2+Spring3 加上@RequiresPermissions 后@Autowired失效问题!
Shiro 权限注解属性详解
- @RequiresAuthentication:表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。
- @RequiresUser:表示当前Subject已经身份验证或者通过记住我登录的。
- @RequiresGuest:表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
- @RequiresRoles(value={“admin”, “user”}, logical= Logical.AND):表示当前Subject需要角色admin和user。
- @RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR):表示当前Subject需要权限user:a或user:b。
本文案例源代码下载链接:http://pan.baidu.com/s/1nuKpwYP 密码:8k7t

: » Shiro 注解
原创文章,作者:wdmbts,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/251556.html