前几节我们学习了ShIro 的标签和编程式,那现在就来学习下注解的授权吧!
大致有这几个注解:
@RequiresRoles(value={“admin”, “user”}, logical= Logical.AND):表示当前 Subject 需要角色 admin 和user
@RequiresPermissions (value={“user:a”, “user:b”}, logical= Logical.OR):表示当前 Subject 需要权限 user:a 或user:b。
@RequiresAuthentication:表示当前Subject已经通过login 进行了身份验证;即 Subject. isAuthenticated() 返回 true
@RequiresUser:表示当前 Subject 已经身份验证或者通过记住我登录的。
@RequiresGuest:表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。
这里的注解即是可以用在Controller层也可以用在Service,既然这些注解我们都知道什么意思,那么我们就不来进行一一的验证了吧,就验证一个比较常用的吧!eg:@RequiresRoles
我们就把这个注解写在Service层吧!
先来不进行加注解测试:
目录结构:
我们在Controller层加一个方法,同时来调用service层的方法:
//注入service
@Autowired
private AnnotationService annotationService;
@RequestMapping("/testAnnotation")
public String testAnnotation(){
//调用service方法。
annotationService.testAnnotation();
return "redirect:/index.jsp";
}
AnnotationService.java:
public void testAnnotation(){
System.out.println("annotation 注解的测试! ");
}
applicationContext.xml:
<!-- 将annotationService 加入到ioc容器中 -->
<bean id="annotationService" class="com.yiyi.service.AnnotationService"></bean>
这时候我们跑项目,会发现不管是用admin 或者是zhao 用户登录都是可以正常登录的。这个就不进行截图了。
接下来我们来看这个,为了测试这个@RequiresRoles,我们就在service层加入这个注解。
@RequiresRoles(value = { "admin" })
public void testAnnotation(){
System.out.println("annotation 注解的测试! ");
}
接下来我们来测试,先用admin 的用户登录,会发现登录时正常的,在以zhao 的用户登录。这是就报这个错误了:
说明是没有admin这个权限。
其他的注解同这个,大家感兴趣可以测试下。