1.apache shiro权限框架有五个注解
- RequiresAuthentication:使用该注解标注的类,实例,方法在访问或调用时,当前Subject必须在当前session中已经过认证(一般指需要登录)。
- RequiresGuest:使用该注解标注的类,实例,方法在访问或调用时,当前Subject可以是“gust”身份,不需要经过认证或者在原先的session中存在记录。
- RequiresPermissions:当前Subject需要拥有某些特定的权限时,才能执行被该注解标注的方法。如果当前Subject不具有这样的权限,则方法不会被执行。
- RequiresRoles:当前Subject必须拥有所有指定的角色时,才能访问被该注解标注的方法。如果当天Subject不同时拥有所有指定角色,则方法不会执行还会抛出AuthorizationException异常(下面列出解决办法)。
- RequiresUser:当前Subject必须是应用的用户,才能访问或调用被该注解标注的类,实例,方法。
在使用@RequiresRoles注解时,如果没有该权限,则会直接返回500错误,这个时候我们需要抓取这个异常进行处理
@RestControllerAdvice//使用此注解可被spring扫描,一般用来做返回ResponseBody的异常处理切面类
public class RRExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(UnauthorizedException.class)//捕捉权限不足异常
public ResponseEntity<String> headleUnauthenticatedException(UnauthorizedException e){
return new ResponseEntity<String>("权限不足,请联系管理员授权!", HttpStatus.FORBIDDEN);
}
@ExceptionHandler(Exception.class)//捕捉其他异常
public ResponseEntity<String> handleException(Exception e){
logger.error(e.getMessage(), e);
return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
2.在一个Controller有多个shiro注解使用时,会按内定顺序处理,且条件都需要满足(与实际顺序无关)
RequiresRoles
RequiresPermissions
RequiresAuthentication
RequiresUser
RequiresGuest
RequiresRoles的使用
//属于admin角色
@RequiresRoles("admin")
//必须同时属于admin和superAdmin角色
@RequiresRoles({"admin","superAdmin"})
//属于superAdmin或者admin之一;修改logical为OR 即可
@RequiresRoles(value={"admin","superAdmin"},logical=Logical.OR)
RequiresPermissions 的使用
//符合index:hello权限要求
@RequiresPermissions("index:hello")
//必须同时复核index:hello和index:world权限要求
@RequiresPermissions({"index:hello","index:world"})
//符合index:hello或index:world权限要求即可
@RequiresPermissions(value={"index:hello","index:world"},logical=Logical.OR)