Spring Security学习 服务器端方法级权限控制

Spring Security学习 服务器端方法级权限控制


在服务器端我们可以通过 Spring security 提供的注解对方法来进行权限控制。Spring Security 在方法的权限控制上 支持三种类型的注解,JSR-250 注解、@Secured 注解和支持表达式的注解,这三种注解默认都是没有启用的,需要 单独通过 global-method-security 元素的对应属性进行启用

1. 开启注解使用

配置文件
<security:global-method-security jsr250-annotations=“enabled”/>
<security:global-method-security secured-annotations=“enabled”/>
<security:global-method-security pre-post-annotations=“disabled”/>

注解开启
@EnableGlobalMethodSecurity :Spring Security默认是禁用注解的,要想开启注解,需要在继承 WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解,并在该类中将 AuthenticationManager定义为Bean。

2. JSR-250注解

  • @RolesAllowed表示访问对应方法时所应该具有的角色
    示例:
    @RolesAllowed({“USER”, “ADMIN”}) 该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省 略前缀ROLE_,实际的权限可能是ROLE_ADMI

  • @PermitAll表示允许所有的角色进行访问,也就是说不进行权限控制

  • @DenyAll是和PermitAll相反的,表示无论什么角色都不能访问

3.支持表达式的注解

  • @PreAuthorize 在方法调用之前,基于表达式的计算结果来限制对方法的访问
    示例:
    @PreAuthorize("#userId == authentication.principal.userId or hasAuthority(‘ADMIN’)")
    void changePassword(@P(“userId”) long userId ){ }
    这里表示在changePassword方法执行之前,判断方法参数userId的值是否等于principal中保存的当前用户的 userId,或者当前用户是否具有ROLE_ADMIN权限,两种符合其一,就可以访问该方法。

  • @PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
    示例:
    @PostAuthorize
    User getUser(“returnObject.userId == authentication.principal.userId or hasPermission(returnObject, ‘ADMIN’)”);

  • @PostAuthorize 允许方法调用,但是如果表达式计算结果为false,将抛出一个安全性异常
    示例:
    @PostAuthorize User getUser(“returnObject.userId == authentication.principal.userId or hasPermission(returnObject, ‘ADMIN’)”);

  • @PostFilter 允许方法调用,但必须按照表达式来过滤方法的结果

  • @PreFilter 允许方法调用,但必须在进入方法之前过滤输入值

4. @Secured注解

  • @Secured注解标注的方法进行权限控制的支持,其值默认为disabled
    示例:
    @Secured(“IS_AUTHENTICATED_ANONYMOUSLY”)
    public Account readAccount(Long id);
    @Secured(“ROLE_TELLER”)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值