Shiro 集成 Spring 之注解

栏目: Java · 发布时间: 6年前

内容简介:集成 Spring 后我们通过过滤器链来配置每个 URL 需要的权限,但当配置多了以后就会不方便,而且只支持 URL 级别的配置。好在 Shiro 提供了相应的注解用于权限控制,此处使用了 Spring MVC 来测试Shiro注解,当然 Shiro 注解不仅仅可以在 web 环境使用,在独立的JavaSE 中也是可以用的,此处只是以 web 为例了。首先我们需要在

集成 Spring 后我们通过过滤器链来配置每个 URL 需要的权限,但当配置多了以后就会不方便,而且只支持 URL 级别的配置。

好在 Shiro 提供了相应的注解用于权限控制,此处使用了 Spring MVC 来测试Shiro注解,当然 Shiro 注解不仅仅可以在 web 环境使用,在独立的JavaSE 中也是可以用的,此处只是以 web 为例了。

开启注解配置

首先我们需要在 Spring Web 的配置文件 spring-web.xml 中加入以下内容来开启 Shiro 的注解支持 :

<aop:config proxy-target-class="true"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

简单演示

接着我们就可以使用注解来配置权限:

@RestController
public class AuthorizationController {

    @RequestMapping("/role1")
    @RequiresRoles("user")
    public String role1() {
        return "success";
    }

    @RequestMapping("/role2")
    @RequiresRoles("admin")
    public String role2() {
        return "success2";
    }
}

访问 role1 方法需要当前用户有 user 角色, role2 方法需要 admin 角色。

当验证失败时,会抛出 UnauthorizedException ,我们可以使用 Spring 的 ExceptionHandler 来进行异常处理:

@ExceptionHandler(UnauthorizedException.class)
public String processUnauthorizedException(UnauthorizedException e) {
    return e.getMessage();
}

更多注解

当然不止有 @RequiresRoles 用来验证角色,Shiro 还提供了以下注解:

@RequiresAuthentication

验证用户是否登陆,等同于方法 subject.isAuthenticated() 。

@RequiresUser

验证用户是否被 记忆 ,即登陆成功或 RememberMe 状态。等同于方法 : subject.isAuthenticated()subject.isRemembered()

@RequiresGuest

仅未登录状态可访问,与 @RequiresUser 完全相反。

@RequiresPermissions

验证是否具备权限,可通过参数 logical 来配置验证策略:

// 拥有 admin 或 user 角色即可
@RequiresPermissions(logical = Logical.OR,value = {"admin", "user"})
// 需同时具备 admin 与 user 角色
@RequiresPermissions(logical = Logical.AND,value = {"admin", "user"})

RequiresRoles 同样可以配置验证策略。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Uberland

Uberland

Alex Rosenblat / University of California Press / 2018-11-19 / GBP 21.00

Silicon Valley technology is transforming the way we work, and Uber is leading the charge. An American startup that promised to deliver entrepreneurship for the masses through its technology, Uber ins......一起来看看 《Uberland》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具