Spring Security教程之基于表达式的权限控制(九)-程序员宅基地

技术标签: java  

目录

1.1      通过表达式控制URL权限

1.2      通过表达式控制方法权限

1.2.1     使用@PreAuthorize和@PostAuthorize进行访问控制

1.2.2     使用@PreFilter和@PostFilter进行过滤

1.3      使用hasPermission表达式

 

       Spring Security允许我们在定义URL访问或方法访问所应有的权限时使用Spring EL表达式,在定义所需的访问权限时如果对应的表达式返回结果为true则表示拥有对应的权限,反之则无。Spring Security可用表达式对象的基类是SecurityExpressionRoot,其为我们提供了如下在使用Spring EL表达式对URL或方法进行权限控制时通用的内置表达式。

表达式

描述

hasRole([role])

当前用户是否拥有指定角色。

hasAnyRole([role1,role2])

多个角色是一个以逗号进行分隔的字符串。如果当前用户拥有指定角色中的任意一个则返回true。

hasAuthority([auth])

等同于hasRole

hasAnyAuthority([auth1,auth2])

等同于hasAnyRole

Principle

代表当前用户的principle对象

authentication

直接从SecurityContext获取的当前Authentication对象

permitAll

总是返回true,表示允许所有的

denyAll

总是返回false,表示拒绝所有的

isAnonymous()

当前用户是否是一个匿名用户

isRememberMe()

表示当前用户是否是通过Remember-Me自动登录的

isAuthenticated()

表示当前用户是否已经登录认证成功了。

isFullyAuthenticated()

如果当前用户既不是一个匿名用户,同时又不是通过Remember-Me自动登录的,则返回true。

 

1.1     通过表达式控制URL权限

       URL的访问权限是通过http元素下的intercept-url元素进行定义的,其access属性用来定义访问配置属性。默认情况下该属性值只能是以字符串进行分隔的字符串列表,且每一个元素都对应着一个角色,因为默认使用的是RoleVoter。通过设置http元素的use-expressions=”true”可以启用intercept-url元素的access属性对Spring EL表达式的支持,use-expressions的值默认为false。启用access属性对Spring EL表达式的支持后每个access属性值都应该是一个返回结果为boolean类型的表达式,当表达式返回结果为true时表示当前用户拥有访问权限。此外WebExpressionVoter将加入AccessDecisionManager的AccessDecisionVoter列表,所以如果不使用NameSpace时应当手动添加WebExpressionVoter到AccessDecisionVoter。

 

   <security:http use-expressions="true">

      <security:form-login/>

      <security:logout/>

      <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />

   </security:http>

 

       在上述配置中我们定义了只有拥有ROLE_USER角色的用户才能访问系统。

       使用表达式控制URL权限使用的表达式对象类是继承自SecurityExpressionRoot的WebSecurityExpressionRoot类。其相比基类而言新增了一个表达式hasIpAddress。hasIpAddress可用来限制只有指定IP或指定范围内的IP才可以访问。

   <security:http use-expressions="true">

      <security:form-login/>

      <security:logout/>

      <security:intercept-url pattern="/**" access="hasRole('ROLE_USER') and hasIpAddress('10.10.10.3')" />

   </security:http>

 

       在上面的配置中我们限制了只有IP为”10.10.10.3”,且拥有ROLE_USER角色的用户才能访问。hasIpAddress是通过Ip地址或子网掩码来进行匹配的。如果要设置10.10.10下所有的子网都可以使用,那么我们对应的hasIpAddress的参数应为“10.10.10.n/24”,其中n可以是合法IP内的任意值。具体规则可以参照hasIpAddress()表达式用于比较的IpAddressMatcher的matches方法源码。以下是IpAddressMatcher的源码。

 

package org.springframework.security.web.util;

 

import java.net.InetAddress;

import java.net.UnknownHostException;

import java.util.Arrays;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.util.StringUtils;

 

/**

 * Matches a request based on IP Address or subnet mask matching against the remote address.

 * <p>

 * Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an IPv4 address will

 * never match a request which returns an IPv6 address, and vice-versa.

 *

 * @author Luke Taylor

 * @since 3.0.2

 */

public final class IpAddressMatcher implements RequestMatcher {

    private final int nMaskBits;

    private final InetAddress requiredAddress;

 

    /**

     * Takes a specific IP address or a range specified using the

     * IP/Netmask (e.g. 192.168.1.0/24 or 202.24.0.0/14).

     *

     * @param ipAddress the address or range of addresses from which the request must come.

     */

    public IpAddressMatcher(String ipAddress) {

 

        if (ipAddress.indexOf('/') > 0) {

            String[] addressAndMask = StringUtils.split(ipAddress, "/");

            ipAddress = addressAndMask[0];

            nMaskBits = Integer.parseInt(addressAndMask[1]);

        } else {

            nMaskBits = -1;

        }

        requiredAddress = parseAddress(ipAddress);

    }

 

    public boolean matches(HttpServletRequest request) {

        return matches(request.getRemoteAddr());

    }

 

    public boolean matches(String address) {

        InetAddress remoteAddress = parseAddress(address);

 

        if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {

            return false;

        }

 

        if (nMaskBits < 0) {

            return remoteAddress.equals(requiredAddress);

        }

 

        byte[] remAddr = remoteAddress.getAddress();

        byte[] reqAddr = requiredAddress.getAddress();

 

        int oddBits = nMaskBits % 8;

        int nMaskBytes = nMaskBits/8 + (oddBits == 0 ? 0 : 1);

        byte[] mask = newbyte[nMaskBytes];

 

        Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte)0xFF);

 

        if (oddBits != 0) {

            int finalByte = (1 << oddBits) - 1;

            finalByte <<= 8-oddBits;

            mask[mask.length - 1] = (byte) finalByte;

        }

 

 //       System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));

 

        for (int i=0; i < mask.length; i++) {

            if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {

                return alse;

            }

        }

 

        return true;

    }

 

    private InetAddress parseAddress(String address) {

        try {

            return InetAddress.getByName(address);

        } catch (UnknownHostException e) {

            thrownew IllegalArgumentException("Failed to parse address" + address, e);

        }

    }

}

  

1.2     通过表达式控制方法权限

       Spring Security中定义了四个支持使用表达式的注解,分别是@PreAuthorize、@PostAuthorize、@PreFilter和@PostFilter。其中前两者可以用来在方法调用前或者调用后进行权限检查,后两者可以用来对集合类型的参数或者返回值进行过滤。要使它们的定义能够对我们的方法的调用产生影响我们需要设置global-method-security元素的pre-post-annotations=”enabled”,默认为disabled。

   <security:global-method-security pre-post-annotations="disabled"/>

 

1.2.1使用@PreAuthorize和@PostAuthorize进行访问控制

 

      @PreAuthorize可以用来控制一个方法是否能够被调用。

@Service

public class UserServiceImpl implements UserService {

 

   @PreAuthorize("hasRole('ROLE_ADMIN')")

   public void addUser(User user) {

      System.out.println("addUser................" + user);

   }

 

   @PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")

   public User find(int id) {

      System.out.println("find user by id............." + id);

      return null;

   }

 

}

         在上面的代码中我们定义了只有拥有角色ROLE_ADMIN的用户才能访问adduser()方法,而访问find()方法需要有ROLE_USER角色或ROLE_ADMIN角色。使用表达式时我们还可以在表达式中使用方法参数。

 

public class UserServiceImpl implements UserService {

 

   /**

    * 限制只能查询Id小于10的用户

    */

   @PreAuthorize("#id<10")

   public User find(int id) {

      System.out.println("find user by id........." + id);

      return null;

   }

  

   /**

    * 限制只能查询自己的信息

    */

   @PreAuthorize("principal.username.equals(#username)")

   public User find(String username) {

      System.out.println("find user by username......" + username);

      return null;

   }

 

   /**

    * 限制只能新增用户名称为abc的用户

    */

   @PreAuthorize("#user.name.equals('abc')")

   public void add(User user) {

      System.out.println("addUser............" + user);

   }

 

}

  

     在上面代码中我们定义了调用find(int id)方法时,只允许参数id小于10的调用;调用find(String username)时只允许username为当前用户的用户名;定义了调用add()方法时只有当参数user的name为abc时才可以调用。

 

       有时候可能你会想在方法调用完之后进行权限检查,这种情况比较少,但是如果你有的话,Spring Security也为我们提供了支持,通过@PostAuthorize可以达到这一效果。使用@PostAuthorize时我们可以使用内置的表达式returnObject表示方法的返回值。我们来看下面这一段示例代码。

 

   @PostAuthorize("returnObject.id%2==0")

   public User find(int id) {

      User user = new User();

      user.setId(id);

      return user;

   }

       上面这一段代码表示将在方法find()调用完成后进行权限检查,如果返回值的id是偶数则表示校验通过,否则表示校验失败,将抛出AccessDeniedException。       需要注意的是@PostAuthorize是在方法调用完成后进行权限检查,它不能控制方法是否能被调用,只能在方法调用完成后检查权限决定是否要抛出AccessDeniedException。

 

1.2.2使用@PreFilter和@PostFilter进行过滤

       使用@PreFilter和@PostFilter可以对集合类型的参数或返回值进行过滤。使用@PreFilter和@PostFilter时,Spring Security将移除使对应表达式的结果为false的元素。

  @PostFilter("filterObject.id%2==0")

   public List<User> findAll() {

      List<User> userList = new ArrayList<User>();

      User user;

      for (int i=0; i<10; i++) {

         user = new User();

         user.setId(i);

         userList.add(user);

      }

      return userList;

   }

  

      上述代码表示将对返回结果中id不为偶数的user进行移除。filterObject是使用@PreFilter和@PostFilter时的一个内置表达式,表示集合中的当前对象。当@PreFilter标注的方法拥有多个集合类型的参数时,需要通过@PreFilter的filterTarget属性指定当前@PreFilter是针对哪个参数进行过滤的。如下面代码就通过filterTarget指定了当前@PreFilter是用来过滤参数ids的。

   @PreFilter(filterTarget="ids", value="filterObject%2==0")

   public void delete(List<Integer> ids, List<String> usernames) {

      ...

   }

 

1.3     使用hasPermission表达式

       Spring Security为我们定义了hasPermission的两种使用方式,它们分别对应着PermissionEvaluator的两个不同的hasPermission()方法。Spring Security默认处理Web、方法的表达式处理器分别为DefaultWebSecurityExpressionHandler和DefaultMethodSecurityExpressionHandler,它们都继承自AbstractSecurityExpressionHandler,其所持有的PermissionEvaluator是DenyAllPermissionEvaluator,其对于所有的hasPermission表达式都将返回false。所以当我们要使用表达式hasPermission时,我们需要自已手动定义SecurityExpressionHandler对应的bean定义,然后指定其PermissionEvaluator为我们自己实现的PermissionEvaluator,然后通过global-method-security元素或http元素下的expression-handler元素指定使用的SecurityExpressionHandler为我们自己手动定义的那个bean。

       接下来看一个自己实现PermissionEvaluator使用hasPermission()表达式的简单示例。

       首先实现自己的PermissionEvaluator,如下所示:

public class MyPermissionEvaluator implements PermissionEvaluator {

 

   public boolean hasPermission(Authentication authentication,

         Object targetDomainObject, Object permission) {

      if ("user".equals(targetDomainObject)) {

         return this.hasPermission(authentication, permission);

      }

      return false;

   }

 

   /**

    * 总是认为有权限

    */

   public boolean hasPermission(Authentication authentication,

         Serializable targetId, String targetType, Object permission) {

      return true;

   }

  

   /**

    * 简单的字符串比较,相同则认为有权限

    */

   private boolean hasPermission(Authentication authentication, Object permission) {

      Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

      for (GrantedAuthority authority : authorities) {

         if (authority.getAuthority().equals(permission)) {

            returntrue;

         }

      }

      return false;

   }

 

}

  

 

       接下来在ApplicationContext中显示的配置一个将使用PermissionEvaluator的SecurityExpressionHandler实现类,然后指定其所使用的PermissionEvaluator为我们自己实现的那个。这里我们选择配置一个针对于方法调用使用的表达式处理器,DefaultMethodSecurityExpressionHandler,具体如下所示。

   <bean id="expressionHandler"

  class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">

      <property name="permissionEvaluator" ref="myPermissionEvaluator" />

   </bean>

   <!-- 自定义的PermissionEvaluator实现 -->

   <bean id="myPermissionEvaluator" class="com.xxx.MyPermissionEvaluator"/>

 

       有了SecurityExpressionHandler之后,我们还要告诉Spring Security,在使用SecurityExpressionHandler时应该使用我们显示配置的那个,这样我们自定义的PermissionEvaluator才能起作用。因为我们上面定义的是针对于方法的SecurityExpressionHandler,所以我们要指定在进行方法权限控制时应该使用它来进行处理,同时注意设置pre-post-annotations=”true”以启用对支持使用表达式的@PreAuthorize等注解的支持。

   <security:global-method-security

      pre-post-annotations="enabled">

      <security:expression-handler ref="expressionHandler" />

   </security:global-method-security>

 

       之后我们就可以在需要进行权限控制的方法上使用@PreAuthorize以及hasPermission()表达式进行权限控制了。

@Service

public class UserServiceImpl implements UserService {

 

   /**

    * 将使用方法hasPermission(Authentication authentication,

         Object targetDomainObject, Object permission)进行验证。

    */

   @PreAuthorize("hasPermission('user', 'ROLE_USER')")

   public User find(int id) {

      return null;

   }

  

   /**

    * 将使用PermissionEvaluator的第二个方法,即hasPermission(Authentication authentication,

         Serializable targetId, String targetType, Object permission)进行验证。

    */

   @PreAuthorize("hasPermission('targetId','targetType','permission')")

   public User find(String username) {

      return null;

   }

 

   @PreAuthorize("hasPermission('user', 'ROLE_ADMIN')")

   public void add(User user) {

 

   }

 

}

  

       在上面的配置中,find(int id)和add()方法将使用PermissionEvaluator中接收三个参数的hasPermission()方法进行验证,而find(String username)方法将使用四个参数的hasPermission()方法进行验证。因为hasPermission()表达式与PermissionEvaluator中hasPermission()方法的对应关系就是在hasPermission()表达式使用的参数基础上加上当前Authentication对象调用对应的hasPermission()方法进行验证。

 

       其实Spring Security已经针对于ACL实现了一个AclPermissionEvaluator。关于ACL的内容将在后文进行介绍。

 

(注:本文是基于Spring Security3.1.6所写)

——————————————
作者:lanfeng2291564 
来源:博客园
原文:https://www.cnblogs.com/fenglan/p/5913463.html 

 

SpringSecurity【注解对方法的权限控制+@PreAuthorize无效】

首先如果你权限限制的方法在某个bean里面,并且,这个bean由SpringMVC管理,那么我们打开SpringSecurity的配置扫描,就写在SpringMVC的配置文件中!!!

反之,如果权限限制的方法在某个bean里面,并且这个bean由Spring管理,那么就配置在Spring的配置文件中!!!

同时,在SpringMVC的配置文件头需要加上spring-security的声明

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
	...


<!-- 开启 SpringSecurity 注解,注意,该注解必须写在SpringMVC的配置文件中,否则 SpringSecurity 的注解会无效! -->
<security:global-method-security pre-post-annotations="enabled"
    jsr250-annotations="enabled" secured-annotations="enabled"
/>    

</beans:beans>

  


在方法执行之前进行方法权限校验:

@PreAuthorize("hasAnyRole('ROLE_USER')")
public User findUserByUsername(User user);

——————————————
作者:Silence_Mind
来源:CSDN
原文:https://blog.csdn.net/Marvel__Dead/article/details/77154356

 

转载于:https://www.cnblogs.com/ryelqy/p/10283256.html

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_30846599/article/details/95050206

智能推荐

艾美捷Epigentek DNA样品的超声能量处理方案-程序员宅基地

文章浏览阅读15次。空化气泡的大小和相应的空化能量可以通过调整完全标度的振幅水平来操纵和数字控制。通过强调超声技术中的更高通量处理和防止样品污染,Epigentek EpiSonic超声仪可以轻松集成到现有的实验室工作流程中,并且特别适合与表观遗传学和下一代应用的兼容性。Epigentek的EpiSonic已成为一种有效的剪切设备,用于在染色质免疫沉淀技术中制备染色质样品,以及用于下一代测序平台的DNA文库制备。该装置的经济性及其多重样品的能力使其成为每个实验室拥有的经济高效的工具,而不仅仅是核心设施。

11、合宙Air模块Luat开发:通过http协议获取天气信息_合宙获取天气-程序员宅基地

文章浏览阅读4.2k次,点赞3次,收藏14次。目录点击这里查看所有博文  本系列博客,理论上适用于合宙的Air202、Air268、Air720x、Air720S以及最近发布的Air720U(我还没拿到样机,应该也能支持)。  先不管支不支持,如果你用的是合宙的模块,那都不妨一试,也许会有意外收获。  我使用的是Air720SL模块,如果在其他模块上不能用,那就是底层core固件暂时还没有支持,这里的代码是没有问题的。例程仅供参考!..._合宙获取天气

EasyMesh和802.11s对比-程序员宅基地

文章浏览阅读7.7k次,点赞2次,收藏41次。1 关于meshMesh的意思是网状物,以前读书的时候,在自动化领域有传感器自组网,zigbee、蓝牙等无线方式实现各个网络节点消息通信,通过各种算法,保证整个网络中所有节点信息能经过多跳最终传递到目的地,用于数据采集。十多年过去了,在无线路由器领域又把这个mesh概念翻炒了一下,各大品牌都推出了mesh路由器,大多数是3个为一组,实现在面积较大的住宅里,增强wifi覆盖范围,智能在多热点之间切换,提升上网体验。因为节点基本上在3个以内,所以mesh的算法不必太复杂,组网形式比较简单。各厂家都自定义了组_802.11s

线程的几种状态_线程状态-程序员宅基地

文章浏览阅读5.2k次,点赞8次,收藏21次。线程的几种状态_线程状态

stack的常见用法详解_stack函数用法-程序员宅基地

文章浏览阅读4.2w次,点赞124次,收藏688次。stack翻译为栈,是STL中实现的一个后进先出的容器。要使用 stack,应先添加头文件include<stack>,并在头文件下面加上“ using namespacestd;"1. stack的定义其定义的写法和其他STL容器相同, typename可以任意基本数据类型或容器:stack<typename> name;2. stack容器内元素的访问..._stack函数用法

2018.11.16javascript课上随笔(DOM)-程序员宅基地

文章浏览阅读71次。<li> <a href = "“#”>-</a></li><li>子节点:文本节点(回车),元素节点,文本节点。不同节点树:  节点(各种类型节点)childNodes:返回子节点的所有子节点的集合,包含任何类型、元素节点(元素类型节点):child。node.getAttribute(at...

随便推点

layui.extend的一点知识 第三方模块base 路径_layui extend-程序员宅基地

文章浏览阅读3.4k次。//config的设置是全局的layui.config({ base: '/res/js/' //假设这是你存放拓展模块的根目录}).extend({ //设定模块别名 mymod: 'mymod' //如果 mymod.js 是在根目录,也可以不用设定别名 ,mod1: 'admin/mod1' //相对于上述 base 目录的子目录}); //你也可以忽略 base 设定的根目录,直接在 extend 指定路径(主要:该功能为 layui 2.2.0 新增)layui.exten_layui extend

5G云计算:5G网络的分层思想_5g分层结构-程序员宅基地

文章浏览阅读3.2k次,点赞6次,收藏13次。分层思想分层思想分层思想-1分层思想-2分层思想-2OSI七层参考模型物理层和数据链路层物理层数据链路层网络层传输层会话层表示层应用层OSI七层模型的分层结构TCP/IP协议族的组成数据封装过程数据解封装过程PDU设备与层的对应关系各层通信分层思想分层思想-1在现实生活种,我们在喝牛奶时,未必了解他的生产过程,我们所接触的或许只是从超时购买牛奶。分层思想-2平时我们在网络时也未必知道数据的传输过程我们的所考虑的就是可以传就可以,不用管他时怎么传输的分层思想-2将复杂的流程分解为几个功能_5g分层结构

基于二值化图像转GCode的单向扫描实现-程序员宅基地

文章浏览阅读191次。在激光雕刻中,单向扫描(Unidirectional Scanning)是一种雕刻技术,其中激光头只在一个方向上移动,而不是来回移动。这种移动方式主要应用于通过激光逐行扫描图像表面的过程。具体而言,单向扫描的过程通常包括以下步骤:横向移动(X轴): 激光头沿X轴方向移动到图像的一侧。纵向移动(Y轴): 激光头沿Y轴方向开始逐行移动,刻蚀图像表面。这一过程是单向的,即在每一行上激光头只在一个方向上移动。返回横向移动: 一旦一行完成,激光头返回到图像的一侧,准备进行下一行的刻蚀。

算法随笔:强连通分量-程序员宅基地

文章浏览阅读577次。强连通:在有向图G中,如果两个点u和v是互相可达的,即从u出发可以到达v,从v出发也可以到达u,则成u和v是强连通的。强连通分量:如果一个有向图G不是强连通图,那么可以把它分成躲个子图,其中每个子图的内部是强连通的,而且这些子图已经扩展到最大,不能与子图外的任一点强连通,成这样的一个“极大连通”子图是G的一个强连通分量(SCC)。强连通分量的一些性质:(1)一个点必须有出度和入度,才会与其他点强连通。(2)把一个SCC从图中挖掉,不影响其他点的强连通性。_强连通分量

Django(2)|templates模板+静态资源目录static_django templates-程序员宅基地

文章浏览阅读3.9k次,点赞5次,收藏18次。在做web开发,要给用户提供一个页面,页面包括静态页面+数据,两者结合起来就是完整的可视化的页面,django的模板系统支持这种功能,首先需要写一个静态页面,然后通过python的模板语法将数据渲染上去。1.创建一个templates目录2.配置。_django templates

linux下的GPU测试软件,Ubuntu等Linux系统显卡性能测试软件 Unigine 3D-程序员宅基地

文章浏览阅读1.7k次。Ubuntu等Linux系统显卡性能测试软件 Unigine 3DUbuntu Intel显卡驱动安装,请参考:ATI和NVIDIA显卡请在软件和更新中的附加驱动中安装。 这里推荐: 运行后,F9就可评分,已测试显卡有K2000 2GB 900+分,GT330m 1GB 340+ 分,GT620 1GB 340+ 分,四代i5核显340+ 分,还有写博客的小盒子100+ 分。relaybot@re...

推荐文章

热门文章

相关标签