欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring 整合Shiro 并扩展使用EL表达式的实例详解

程序员文章站 2023-01-15 10:29:37
shiro是一个轻量级的权限控制框架,应用非常广泛。本文的重点是介绍spring整合shiro,并通过扩展使用spring的el表达式,使@requiresroles等支持...

shiro是一个轻量级的权限控制框架,应用非常广泛。本文的重点是介绍spring整合shiro,并通过扩展使用spring的el表达式,使@requiresroles等支持动态的参数。对shiro的介绍则不在本文的讨论范围之内,读者如果有对shiro不是很了解的,可以通过其官方网站了解相应的信息。infoq上也有一篇文章对shiro介绍比较全面的,也是官方推荐的,其地址是。

shiro整合spring

首先需要在你的工程中加入shiro-spring-xxx.jar,如果是使用maven管理你的工程,则可以在你的依赖中加入以下依赖,笔者这里是选择的当前最新的1.4.0版本。

<dependency>
 <groupid>org.apache.shiro</groupid>
 <artifactid>shiro-spring</artifactid>
 <version>1.4.0</version>
</dependency>

接下来需要在你的web.xml中定义一个shirofilter,应用它来拦截所有的需要权限控制的请求,通常是配置为/*。另外该filter需要加入最前面,以确保请求进来后最先通过shiro的权限控制。这里的filter对应的class配置的是delegatingfilterproxy,这是spring提供的一个filter的代理,可以使用spring bean容器中的一个bean来作为当前的filter实例,对应的bean就会取filter-name对应的那个bean。所以下面的配置会到bean容器中寻找一个名为shirofilter的bean。

<filter>
 <filter-name>shirofilter</filter-name>
 <filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class>
 <init-param>
  <param-name>targetfilterlifecycle</param-name>
  <param-value>true</param-value>
 </init-param>
</filter>
<filter-mapping>
 <filter-name>shirofilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

独立使用shiro时通常会定义一个org.apache.shiro.web.servlet.shirofilter来做类似的事。

接下来就是在bean容器中定义我们的shirofilter了。如下我们定义了一个shirofilterfactorybean,其会产生一个abstractshirofilter类型的bean。通过shirofilterfactorybean我们可以指定一个securitymanager,这里使用的defaultwebsecuritymanager需要指定一个realm,如果需要指定多个realm则通过realms指定。这里简单起见就直接使用基于文本定义的textconfigurationrealm。通过loginurl指定登录地址、successurl指定登录成功后需要跳转的地址,unauthorizedurl指定权限不足时的提示页面。filterchaindefinitions则定义url与需要使用的filter之间的关系,等号右边的是filter的别名,默认的别名都定义在org.apache.shiro.web.filter.mgt.defaultfilter这个枚举类中。

<bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean">
 <property name="securitymanager" ref="securitymanager"/>
 <property name="loginurl" value="/login.jsp"/>
 <property name="successurl" value="/home.jsp"/>
 <property name="unauthorizedurl" value="/unauthorized.jsp"/>
 <property name="filterchaindefinitions">
  <value>
   /admin/** = authc, roles[admin]
   /logout = logout
   # 其它地址都要求用户已经登录了
   /** = authc,logger
  </value>
 </property>
</bean>
<bean id="securitymanager" class="org.apache.shiro.web.mgt.defaultwebsecuritymanager">
 <property name="realm" ref="realm"/>
</bean>
<bean id="lifecyclebeanpostprocessor" class="org.apache.shiro.spring.lifecyclebeanpostprocessor"/>
<!-- 简单起见,这里就使用基于文本的realm实现 -->
<bean id="realm" class="org.apache.shiro.realm.text.textconfigurationrealm">
 <property name="userdefinitions">
  <value>
   user1=pass1,role1,role2
   user2=pass2,role2,role3
   admin=admin,admin
  </value>
 </property>
</bean>

如果需要在filterchaindefinitions定义中使用自定义的filter,则可以通过shirofilterfactorybean的filters指定自定义的filter及其别名映射关系。比如下面这样我们新增了一个别名为logger的filter,并在filterchaindefinitions中指定了/**需要应用别名为logger的filter。

<bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean">
 <property name="securitymanager" ref="securitymanager"/>
 <property name="loginurl" value="/login.jsp"/>
 <property name="successurl" value="/home.jsp"/>
 <property name="unauthorizedurl" value="/unauthorized.jsp"/>
 <property name="filters">
  <util:map>
   <entry key="logger">
    <bean class="com.elim.chat.shiro.filter.loggerfilter"/>
   </entry>
  </util:map>
 </property>
 <property name="filterchaindefinitions">
  <value>
   /admin/** = authc, roles[admin]
   /logout = logout
   # 其它地址都要求用户已经登录了
   /** = authc,logger
  </value>
 </property>
</bean>

其实我们需要应用的filter别名定义也可以不直接通过shirofilterfactorybean的setfilters()来指定,而是直接在对应的bean容器中定义对应的filter对应的bean。因为默认情况下,shirofilterfactorybean会把bean容器中的所有的filter类型的bean以其id为别名注册到filters中。所以上面的定义等价于下面这样。

<bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean">
 <property name="securitymanager" ref="securitymanager"/>
 <property name="loginurl" value="/login.jsp"/>
 <property name="successurl" value="/home.jsp"/>
 <property name="unauthorizedurl" value="/unauthorized.jsp"/>
 <property name="filterchaindefinitions">
  <value>
   /admin/** = authc, roles[admin]
   /logout = logout
   # 其它地址都要求用户已经登录了
   /** = authc,logger
  </value>
 </property>
</bean>
<bean id="logger" class="com.elim.chat.shiro.filter.loggerfilter"/>

经过以上几步,shiro和spring的整合就完成了,这个时候我们请求工程的任意路径都会要求我们登录,且会自动跳转到loginurl指定的路径让我们输入用户名/密码登录。这个时候我们应该提供一个表单,通过username获得用户名,通过password获得密码,然后提交登录请求的时候请求需要提交到loginurl指定的地址,但是请求方式需要变为post。登录时使用的用户名/密码是我们在textconfigurationrealm中定义的用户名/密码,基于我们上面的配置则可以使用user1/pass1、admin/admin等。登录成功后就会跳转到successurl参数指定的地址了。如果我们是使用user1/pass1登录的,则我们还可以试着访问一下/admin/index,这个时候会因为权限不足跳转到unauthorized.jsp。

启用基于注解的支持

基本的整合需要我们把url需要应用的权限控制都定义在shirofilterfactorybean的filterchaindefinitions中。这有时候会没那么灵活。shiro为我们提供了整合spring后可以使用的注解,它允许我们在需要进行权限控制的class或method上加上对应的注解以定义访问class或method需要的权限,如果是定义中class上的,则表示调用该class中所有的方法都需要对应的权限(注意需要是外部调用,这是动态代理的局限)。要使用这些注解我们需要在spring的bean容器中添加下面两个bean定义,这样才能在运行时根据注解定义来判断用户是否拥有对应的权限。这是通过spring的aop机制来实现的,关于spring aop如果有不是特别了解的,可以参考笔者写在iteye的《spring aop介绍专栏》。下面的两个bean定义,authorizationattributesourceadvisor是定义了一个advisor,其会基于shiro提供的注解配置的方法进行拦截,校验权限。defaultadvisorautoproxycreator则是提供了为标注有shiro提供的权限控制注解的class创建代理对象,并在拦截到目标方法调用时应用authorizationattributesourceadvisor的功能。当拦截到了用户的一个请求,而该用户没有对应方法或类上标注的权限时,将抛出org.apache.shiro.authz.authorizationexception异常。

<bean class="org.springframework.aop.framework.autoproxy.defaultadvisorautoproxycreator" 
 depends-on="lifecyclebeanpostprocessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.authorizationattributesourceadvisor">
 <property name="securitymanager" ref="securitymanager"/>
</bean>

如果我们的bean容器中已经定义了<aop:config/>或<aop:aspectj-autoproxy/>,则可以不再定义defaultadvisorautoproxycreator。因为前面两种情况都会自动添加与defaultadvisorautoproxycreator类似的bean。关于defaultadvisorautoproxycreator的更多介绍也可以参考笔者的spring aop自动创建代理对象的原理这篇博客。

shiro提供的权限控制注解如下:

requiresauthentication:需要用户在当前会话中是被认证过的,即需要通过用户名/密码登录过,不包括rememberme自动登录。

requiresuser:需要用户是被认证过的,可以是在本次会话中通过用户名/密码登录认证,也可以是通过rememberme自动登录。

requiresguest:需要用户是未登录的。
requiresroles:需要用户拥有指定的角色。
requirespermissions:需要用户拥有指定的权限。

前面三个都很好理解,而后面两个是类似的。笔者这里拿@requirespermissions来做个示例。首先我们把上面定义的realm改一下,给role添加权限。这样我们的user1将拥有perm1、perm2和perm3的权限,而user2将拥有perm1、perm3和perm4的权限。

<bean id="realm" class="org.apache.shiro.realm.text.textconfigurationrealm">
 <property name="userdefinitions">
  <value>
   user1=pass1,role1,role2
   user2=pass2,role2,role3
   admin=admin,admin
  </value>
 </property>
 <property name="roledefinitions">
  <value>
   role1=perm1,perm2
   role2=perm1,perm3
   role3=perm3,perm4
  </value>
 </property>
</bean>

@requirespermissions可以添加在方法上,用来指定调用该方法时需要拥有的权限。下面的代码我们就指定了在访问/perm1时必须拥有perm1这个权限。这个时候user1和user2都能访问。

@requestmapping("/perm1")
@requirespermissions("perm1")
public object permission1() {
 return "permission1";
}

如果需要指定必须同时拥有多个权限才能访问某个方法,可以把需要指定的权限以数组的形式指定(注解上的数组属性指定单个的时候可以不加大括号,需要指定多个时就需要加大括号)。比如下面这样我们就指定了在访问/perm1andperm4时用户必须同时拥有perm1和perm4这两个权限。这时候就只有user2可以访问,因为只有它才同时拥有perm1和perm4。

@requestmapping("/perm1andperm4")
@requirespermissions({"perm1", "perm4"})
public object perm1andperm4() {
 return "perm1andperm4";
}

当同时指定了多个权限时,默认多个权限之间的关系是与的关系,即需要同时拥有指定的所有的权限。如果只需要拥有指定的多个权限中的一个就可以访问,则我们可以通过logical=logical.or指定多个权限之间是或的关系。比如下面这样我们就指定了在访问/perm1orperm4时只需要拥有perm1或perm4权限即可,这样user1和user2都可以访问该方法。

@requestmapping("/perm1orperm4")
@requirespermissions(value={"perm1", "perm4"}, logical=logical.or)
public object perm1orperm4() {
 return "perm1orperm4";
}

@requirespermissions也可以标注在class上,表示在外部访问class中的方法时都需要有对应的权限。比如下面这样我们在class级别指定了需要拥有权限perm2,而在index()方法上则没有指定需要任何权限,但是我们在访问该方法时还是需要拥有class级别指定的权限。此时将只有user1可以访问。

@restcontroller
@requestmapping("/foo")
@requirespermissions("perm2")
public class foocontroller {
 @requestmapping(method=requestmethod.get)
 public object index() {
  map<string, object> map = new hashmap<>();
  map.put("abc", 123);
  return map;
 }
}

当class和方法级别都同时拥有@requirespermissions时,方法级别的拥有更高的优先级,而且此时将只会校验方法级别要求的权限。如下我们在class级别指定了需要perm2权限,而在方法级别指定了需要perm3权限,那么在访问/foo时将只需要拥有perm3权限即可访问到index()方法。所以此时user1和user2都可以访问/foo。

@restcontroller
@requestmapping("/foo")
@requirespermissions("perm2")
public class foocontroller {
 @requestmapping(method=requestmethod.get)
 @requirespermissions("perm3")
 public object index() {
  map<string, object> map = new hashmap<>();
  map.put("abc", 123);
  return map;
 }
}

但是如果此时我们在class上新增@requiresroles("role1")指定需要拥有角色role1,那么此时访问/foo时需要拥有class上的role1和index()方法上@requirespermissions("perm3")指定的perm3权限。因为requiresroles和requirespermissions属于不同维度的权限定义,shiro在校验的时候都将校验一遍,但是如果class和方法上都拥有同类型的权限控制定义的注解时,则只会以方法上的定义为准。

@restcontroller
@requestmapping("/foo")
@requirespermissions("perm2")
@requiresroles("role1")
public class foocontroller {
 @requestmapping(method=requestmethod.get)
 @requirespermissions("perm3")
 public object index() {
  map<string, object> map = new hashmap<>();
  map.put("abc", 123);
  return map;
 }
}

虽然示例中使用的只是requirespermissions,但是其它权限控制注解的用法也是类似的,其它注解的用法请感兴趣的朋友自己实践。

基于注解控制权限的原理

上面使用@requirespermissions我们指定的权限都是静态的,写本文的一个主要目的是介绍一种方法,通过扩展实现来使指定的权限可以是动态的。但是在扩展前我们得知道它底层的工作方式,即实现原理,我们才能进行扩展。所以接下来我们先来看一下shiro整合spring后使用@requirespermissions的工作原理。在启用对@requirespermissions的支持时我们定义了如下bean,这是一个advisor,其继承自staticmethodmatcherpointcutadvisor,它的方法匹配逻辑是只要class或method上拥有shiro的几个权限控制注解即可,而拦截以后的处理逻辑则是由相应的advice指定。

<bean class="org.apache.shiro.spring.security.interceptor.authorizationattributesourceadvisor">
 <property name="securitymanager" ref="securitymanager"/>
</bean>

以下是authorizationattributesourceadvisor的源码。我们可以看到在其构造方法中通过setadvice()指定了aopallianceannotationsauthorizingmethodinterceptor这个advice实现类,这是基于methodinterceptor的实现。

public class authorizationattributesourceadvisor extends staticmethodmatcherpointcutadvisor {
 private static final logger log = loggerfactory.getlogger(authorizationattributesourceadvisor.class);
 private static final class<? extends annotation>[] authz_annotation_classes =
   new class[] {
     requirespermissions.class, requiresroles.class,
     requiresuser.class, requiresguest.class, requiresauthentication.class
   };
 protected securitymanager securitymanager = null;
 public authorizationattributesourceadvisor() {
  setadvice(new aopallianceannotationsauthorizingmethodinterceptor());
 }
 public securitymanager getsecuritymanager() {
  return securitymanager;
 }
 public void setsecuritymanager(org.apache.shiro.mgt.securitymanager securitymanager) {
  this.securitymanager = securitymanager;
 }
 public boolean matches(method method, class targetclass) {
  method m = method;
  if ( isauthzannotationpresent(m) ) {
   return true;
  }
  //the 'method' parameter could be from an interface that doesn't have the annotation.
  //check to see if the implementation has it.
  if ( targetclass != null) {
   try {
    m = targetclass.getmethod(m.getname(), m.getparametertypes());
    return isauthzannotationpresent(m) || isauthzannotationpresent(targetclass);
   } catch (nosuchmethodexception ignored) {
    //default return value is false. if we can't find the method, then obviously
    //there is no annotation, so just use the default return value.
   }
  }
  return false;
 }
 private boolean isauthzannotationpresent(class<?> targetclazz) {
  for( class<? extends annotation> annclass : authz_annotation_classes ) {
   annotation a = annotationutils.findannotation(targetclazz, annclass);
   if ( a != null ) {
    return true;
   }
  }
  return false;
 }
 private boolean isauthzannotationpresent(method method) {
  for( class<? extends annotation> annclass : authz_annotation_classes ) {
   annotation a = annotationutils.findannotation(method, annclass);
   if ( a != null ) {
    return true;
   }
  }
  return false;
 }
}

aopallianceannotationsauthorizingmethodinterceptor的源码如下。其实现的methodinterceptor接口的invoke方法又调用了父类的invoke方法。同时我们要看到在其构造方法中创建了一些authorizingannotationmethodinterceptor实现,这些实现才是实现权限控制的核心,待会我们会挑出permissionannotationmethodinterceptor实现类来看其具体的实现逻辑。

public class aopallianceannotationsauthorizingmethodinterceptor
  extends annotationsauthorizingmethodinterceptor implements methodinterceptor {
 public aopallianceannotationsauthorizingmethodinterceptor() {
  list<authorizingannotationmethodinterceptor> interceptors =
    new arraylist<authorizingannotationmethodinterceptor>(5);
  //use a spring-specific annotation resolver - spring's annotationutils is nicer than the
  //raw jdk resolution process.
  annotationresolver resolver = new springannotationresolver();
  //we can re-use the same resolver instance - it does not retain state:
  interceptors.add(new roleannotationmethodinterceptor(resolver));
  interceptors.add(new permissionannotationmethodinterceptor(resolver));
  interceptors.add(new authenticatedannotationmethodinterceptor(resolver));
  interceptors.add(new userannotationmethodinterceptor(resolver));
  interceptors.add(new guestannotationmethodinterceptor(resolver));
  setmethodinterceptors(interceptors);
 }
 protected org.apache.shiro.aop.methodinvocation createmethodinvocation(object implspecificmethodinvocation) {
  final methodinvocation mi = (methodinvocation) implspecificmethodinvocation;
  return new org.apache.shiro.aop.methodinvocation() {
   public method getmethod() {
    return mi.getmethod();
   }
   public object[] getarguments() {
    return mi.getarguments();
   }
   public string tostring() {
    return "method invocation [" + mi.getmethod() + "]";
   }
   public object proceed() throws throwable {
    return mi.proceed();
   }
   public object getthis() {
    return mi.getthis();
   }
  };
 }
 protected object continueinvocation(object aopalliancemethodinvocation) throws throwable {
  methodinvocation mi = (methodinvocation) aopalliancemethodinvocation;
  return mi.proceed();
 }
 public object invoke(methodinvocation methodinvocation) throws throwable {
  org.apache.shiro.aop.methodinvocation mi = createmethodinvocation(methodinvocation);
  return super.invoke(mi);
 }
}

通过看父类的invoke方法实现,最终我们会看到核心逻辑是调用assertauthorized方法,而该方法的实现(源码如下)又是依次判断配置的authorizingannotationmethodinterceptor是否支持当前方法进行权限校验(通过判断class或method上是否拥有其支持的注解),当支持时则会调用其assertauthorized方法进行权限校验,而authorizingannotationmethodinterceptor又会调用authorizingannotationhandler的assertauthorized方法。

protected void assertauthorized(methodinvocation methodinvocation) throws authorizationexception {
 //default implementation just ensures no deny votes are cast:
 collection<authorizingannotationmethodinterceptor> aamis = getmethodinterceptors();
 if (aamis != null && !aamis.isempty()) {
  for (authorizingannotationmethodinterceptor aami : aamis) {
   if (aami.supports(methodinvocation)) {
    aami.assertauthorized(methodinvocation);
   }
  }
 }
}

接下来我们再回过头来看aopallianceannotationsauthorizingmethodinterceptor的定义的permissionannotationmethodinterceptor,其源码如下。结合aopallianceannotationsauthorizingmethodinterceptor的源码和permissionannotationmethodinterceptor的源码,我们可以看到permissionannotationmethodinterceptor中这时候指定了permissionannotationhandler和springannotationresolver。permissionannotationhandler是authorizingannotationhandler的一个子类。所以我们最终的权限控制由permissionannotationhandler的assertauthorized实现决定。

public class permissionannotationmethodinterceptor extends authorizingannotationmethodinterceptor {
 public permissionannotationmethodinterceptor() {
  super( new permissionannotationhandler() );
 }
 public permissionannotationmethodinterceptor(annotationresolver resolver) {
  super( new permissionannotationhandler(), resolver);
 }
}

接下来我们来看permissionannotationhandler的assertauthorized方法实现,其完整代码如下。从实现上我们可以看到其会从annotation中获取配置的权限值,而这里的annotation就是requirespermissions注解。而且在进行权限校验时都是直接使用的我们定义注解时指定的文本值,待会我们进行扩展时就将从这里入手。

public class permissionannotationhandler extends authorizingannotationhandler {
 public permissionannotationhandler() {
  super(requirespermissions.class);
 }
 protected string[] getannotationvalue(annotation a) {
  requirespermissions rpannotation = (requirespermissions) a;
  return rpannotation.value();
 }
 public void assertauthorized(annotation a) throws authorizationexception {
  if (!(a instanceof requirespermissions)) return;
  requirespermissions rpannotation = (requirespermissions) a;
  string[] perms = getannotationvalue(a);
  subject subject = getsubject();
  if (perms.length == 1) {
   subject.checkpermission(perms[0]);
   return;
  }
  if (logical.and.equals(rpannotation.logical())) {
   getsubject().checkpermissions(perms);
   return;
  }
  if (logical.or.equals(rpannotation.logical())) {
   // avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasrole first
   boolean hasatleastonepermission = false;
   for (string permission : perms) if (getsubject().ispermitted(permission)) hasatleastonepermission = true;
   // cause the exception if none of the role match, note that the exception message will be a bit misleading
   if (!hasatleastonepermission) getsubject().checkpermission(perms[0]);
  }
 }
}

通过前面的介绍我们知道permissionannotationhandler的assertauthorized方法参数的annotation是由authorizingannotationmethodinterceptor在调用authorizingannotationhandler的assertauthorized方法时传递的。其源码如下,从源码中我们可以看到annotation是通过getannotation方法获得的。

public void assertauthorized(methodinvocation mi) throws authorizationexception {
 try {
  ((authorizingannotationhandler)gethandler()).assertauthorized(getannotation(mi));
 }
 catch(authorizationexception ae) {
  if (ae.getcause() == null) ae.initcause(new authorizationexception("not authorized to invoke method: " + mi.getmethod()));
  throw ae;
 }   
}

沿着这个方向走下去,最终我们会找到springannotationresolver的getannotation方法实现,其实现如下。从下面的代码可以看到,其在寻找注解时是优先寻找method上的,如果在method上没有找到会从当前方法调用的所属class上寻找对应的注解。从这里也可以看到为什么我们之前在class和method上都定义了相同类型的权限控制注解时生效的是method上的,而单独存在的时候就是单独定义的那个生效了。

public class springannotationresolver implements annotationresolver {
 public annotation getannotation(methodinvocation mi, class<? extends annotation> clazz) {
  method m = mi.getmethod();
  annotation a = annotationutils.findannotation(m, clazz);
  if (a != null) return a;
  //the methodinvocation's method object could be a method defined in an interface.
  //however, if the annotation existed in the interface's implementation (and not
  //the interface itself), it won't be on the above method object. instead, we need to
  //acquire the method representation from the targetclass and check directly on the
  //implementation itself:
  class<?> targetclass = mi.getthis().getclass();
  m = classutils.getmostspecificmethod(m, targetclass);
  a = annotationutils.findannotation(m, clazz);
  if (a != null) return a;
  // see if the class has the same annotation
  return annotationutils.findannotation(mi.getthis().getclass(), clazz);
 }
}

通过以上的源码阅读,相信读者对于shiro整合spring后支持的权限控制注解的原理已经有了比较深入的理解。上面贴出的源码只是部分笔者认为比较核心的,有想详细了解完整内容的请读者自己沿着笔者提到的思路去阅读完整代码。
了解了这块基于注解进行权限控制的原理后,读者朋友们也可以根据实际的业务需要进行相应的扩展。

扩展使用spring el表达式

假设现在内部有下面这样一个接口,其中有一个query方法,接收一个参数type。这里我们简化一点,假设只要接收这么一个参数,然后对应不同的取值时将返回不同的结果。

public interface realservice {
 object query(int type);
 
}

这个接口是对外开放的,通过对应的url可以请求到该方法,我们定义了对应的controller方法如下:

@requestmapping("/service/{type}")
public object query(@pathvariable("type") int type) {
 return this.realservice.query(type);
}

上面的接口服务在进行查询的时候针对type是有权限的,不是每个用户都可以使用每种type进行查询的,需要拥有对应的权限才行。所以针对上面的处理器方法我们需要加上权限控制,而且在控制时需要的权限是随着参数type动态变的。假设关于type的每项权限的定义是query:type的形式,比如type=1时需要的权限是query:1,type=2时需要的权限是query:2。在没有与spring整合时,我们会如下这样做:

@requestmapping("/service/{type}")
public object query(@pathvariable("type") int type) {
 securityutils.getsubject().checkpermission("query:" + type);
 return this.realservice.query(type);
}

但是与spring整合后,上面的做法耦合性强,我们会更希望通过整合后的注解来进行权限控制。对于上面的场景我们更希望通过@requirespermissions来指定需要的权限,但是@requirespermissions中定义的权限是静态文本,固定的。它没法满足我们动态的需求。这个时候可能你会想着我们可以把controller处理方法拆分为多个,单独进行权限控制。比如下面这样:

@requestmapping("/service/1")
@requirespermissions("query:1")
public object service1() {
 return this.realservice.query(1);
}
@requirespermissions("query:2")
@requestmapping("/service/2")
public object service2() {
 return this.realservice.query(2);
}
//...
@requestmapping("/service/200")
@requirespermissions("query:200")
public object service200() {
 return this.realservice.query(200);
}

这在type的取值范围比较小的时候还可以,但是如果像上面这样可能的取值有200种,把它们穷举出来定义单独的处理器方法并进行权限控制就显得有点麻烦了。另外就是如果将来type的取值有变动,我们还得添加新的处理器方法。所以最好的办法是让@requirespermissions支持动态的权限定义,同时又可以维持静态定义的支持。通过前面的分析我们知道,切入点是permissionannotationhandler,而它里面是没有提供对权限校验的扩展的。我们如果想对它扩展简单的办法就是把它整体的替换。但是我们需要动态处理的权限是跟方法参数相关的,而permissionannotationhandler中是取不到方法参数的,为此我们不能直接替换掉permissionannotationhandler。permissionannotationhandler是由permissionannotationmethodinterceptor调用的,在其父类authorizingannotationmethodinterceptor的assertauthorized方法中调用permissionannotationhandler时是可以获取到方法参数的。为此我们的扩展点就选在permissionannotationmethodinterceptor类上,我们也需要把它整体的替换。spring的el表达式可以支持解析方法参数值,这里我们选择引入spring的el表达式,在@requirespermissions定义权限时可以使用spring el表达式引入方法参数。同时为了兼顾静态的文本。这里引入spring的el表达式模板。关于spring的el表达式模板可以参考笔者的这篇博文。我们定义自己的permissionannotationmethodinterceptor,把它继承自permissionannotationmethodinterceptor,重写assertauthoried方法,方法的实现逻辑参考permissionannotationhandler中的逻辑,但是所使用的@requirespermissions中的权限定义,是我们使用spring el表达式基于当前调用的方法作为evaluationcontext解析后的结果。以下是我们自己定义的permissionannotationmethodinterceptor实现。

public class selfpermissionannotationmethodinterceptor extends permissionannotationmethodinterceptor {
 private final spelexpressionparser parser = new spelexpressionparser();
 private final parameternamediscoverer paramnamediscoverer = new defaultparameternamediscoverer();
 private final templateparsercontext templateparsercontext = new templateparsercontext();
 public selfpermissionannotationmethodinterceptor(annotationresolver resolver) {
  super(resolver);
 }
 @override
 public void assertauthorized(methodinvocation mi) throws authorizationexception {
  annotation annotation = super.getannotation(mi);
  requirespermissions permannotation = (requirespermissions) annotation;
  string[] perms = permannotation.value();
  evaluationcontext evaluationcontext = new methodbasedevaluationcontext(null, mi.getmethod(), mi.getarguments(), paramnamediscoverer);
  for (int i=0; i<perms.length; i++) {
   expression expression = this.parser.parseexpression(perms[i], templateparsercontext);
   //使用spring el表达式解析后的权限定义替换原来的权限定义
   perms[i] = expression.getvalue(evaluationcontext, string.class);
  }
  subject subject = getsubject();
  if (perms.length == 1) {
   subject.checkpermission(perms[0]);
   return;
  }
  if (logical.and.equals(permannotation.logical())) {
   getsubject().checkpermissions(perms);
   return;
  }
  if (logical.or.equals(permannotation.logical())) {
   // avoid processing exceptions unnecessarily - "delay" throwing the exception by calling hasrole first
   boolean hasatleastonepermission = false;
   for (string permission : perms) if (getsubject().ispermitted(permission)) hasatleastonepermission = true;
   // cause the exception if none of the role match, note that the exception message will be a bit misleading
   if (!hasatleastonepermission) getsubject().checkpermission(perms[0]);
  }
 }
}

定义了自己的permissionannotationmethodinterceptor后,我们需要替换原来的permissionannotationmethodinterceptor为我们自己的permissionannotationmethodinterceptor。根据前面介绍的shiro整合spring后使用@requirespermissions等注解的原理我们知道permissionannotationmethodinterceptor是由aopallianceannotationsauthorizingmethodinterceptor指定的,而后者又是由authorizationattributesourceadvisor指定的。为此我们需要在定义authorizationattributesourceadvisor时通过显示定义aopallianceannotationsauthorizingmethodinterceptor的方式显示的定义其中的authorizingannotationmethodinterceptor,然后把自带的permissionannotationmethodinterceptor替换为我们自定义的selfauthorizingannotationmethodinterceptor。替换后的定义如下:

<bean class="org.apache.shiro.spring.security.interceptor.authorizationattributesourceadvisor">
 <property name="securitymanager" ref="securitymanager"/>
 <property name="advice">
  <bean class="org.apache.shiro.spring.security.interceptor.aopallianceannotationsauthorizingmethodinterceptor">
   <property name="methodinterceptors">
    <util:list>
     <bean class="org.apache.shiro.authz.aop.roleannotationmethodinterceptor"
      c:resolver-ref="springannotationresolver"/>
     <!-- 使用自定义的permissionannotationmethodinterceptor -->
     <bean class="com.elim.chat.shiro.selfpermissionannotationmethodinterceptor"
      c:resolver-ref="springannotationresolver"/>
     <bean class="org.apache.shiro.authz.aop.authenticatedannotationmethodinterceptor"
      c:resolver-ref="springannotationresolver"/>
     <bean class="org.apache.shiro.authz.aop.userannotationmethodinterceptor"
      c:resolver-ref="springannotationresolver"/>
     <bean class="org.apache.shiro.authz.aop.guestannotationmethodinterceptor"
      c:resolver-ref="springannotationresolver"/>
    </util:list>
   </property>
  </bean>
 </property>
</bean>

<bean id="springannotationresolver" class="org.apache.shiro.spring.aop.springannotationresolver"/>

为了演示前面示例的动态的权限,我们把角色与权限的关系调整如下,让role1、role2和role3分别拥有query:1、query:2和query:3的权限。此时user1将拥有query:1和query:2的权限。

<bean id="realm" class="org.apache.shiro.realm.text.textconfigurationrealm">
 <property name="userdefinitions">
  <value>
   user1=pass1,role1,role2
   user2=pass2,role2,role3
   admin=admin,admin
  </value>
 </property>
 <property name="roledefinitions">
  <value>
   role1=perm1,perm2,query:1
   role2=perm1,perm3,query:2
   role3=perm3,perm4,query:3
  </value>
 </property>
</bean>

此时@requirespermissions中指定权限时就可以使用spring el表达式支持的语法了。因为我们在定义selfpermissionannotationmethodinterceptor时已经指定了应用基于模板的表达式解析,此时权限中定义的文本都将作为文本解析,动态的部分默认需要使用#{前缀和}后缀包起来(这个前缀和后缀是可以指定的,但是默认就好)。在动态部分中可以使用#前缀引用变量,基于方法的表达式解析中可以使用参数名或p参数索引的形式引用方法参数。所以上面我们需要动态的权限的query方法的@requirespermissions定义如下。

@requestmapping("/service/{type}")
@requirespermissions("query:#{#type}")
public object query(@pathvariable("type") int type) {
 return this.realservice.query(type);
}

这样user1在访问/service/1和/service/2是ok的,但是在访问/service/3和/service/300时会提示没有权限,因为user1没有query:3和query:300的权限。

总结

以上所述是小编给大家介绍的spring 整合shiro 并扩展使用el表达式的实例详解,希望对大家有所帮助