服务器端方法级权限控制

在服务器端我们可以通过Spring security提供的注解对方法来进行权限控制。Spring Security在方法的权限控制上支持三种类型的注解

  • JSR-250注解
  • @Secured注解
  • 支持表达式的注解,

这三种注解默认都是没有启用的,需要
单独通过global-method-security元素的对应属性进行启用

JSR-250注解使用

第一步:在spring-security.xml中配置启用注解

<!--配置开启JSR-250注解-->
<security:global-method-security jsr250-annotations="enabled"/>

第二步:在指定的方法上使用

// 查询所有产品信息
@RequestMapping("/findAll.do")
@RolesAllowed("ADMIN")
public ModelAndView findAll(){
    ModelAndView mv = new ModelAndView();
    List<Product> all = productService.findAll();
    mv.addObject("productList",all);
    mv.setViewName("product-list");
    return mv;
}

第三步:在pom.xml中导入依赖

<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>jsr250-api</artifactId>
    <version>1.0</version>
</dependency>

注:@RolesAllowed({“USER”, “ADMIN”}),这样就能指定多个权限可以使用

@Secured注解

第一步:在spring-security.xml中配置启用注解

<!--配置开启@Secured注解-->
<security:global-method-security secured-annotations="enabled"/>

第二步:在指定的方法上使用

@RequestMapping("/findAll.do")
@Secured("ROLE_USER")
public ModelAndView findAll(){
    ModelAndView mv = new ModelAndView();
    List<Product> all = productService.findAll();
    mv.addObject("productList",all);
    mv.setViewName("product-list");
    return mv;
}

注意:
1、@Secured(“ROLE_USER”),这里前面要加上ROLE_
2、不需要导入依赖

支持表达式的注解

第一步:在spring-security.xml中配置启用注解

<!--配置开启支持表达式的注解-->
<security:global-method-security pre-post-annotations="enabled"/>

第二步:在指定的方法上使用
第一种使用:指定用户

@RequestMapping("/findAll.do")
@PreAuthorize("authentication.principal.username=='tom'")
public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<Product> all = productService.findAll();
        mv.addObject("productList",all);
        mv.setViewName("product-list");
        return mv;
    }

第二种使用:

@RequestMapping("/findAll.do")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView findAll(){
    ModelAndView mv = new ModelAndView();
    List<Product> all = productService.findAll();
    mv.addObject("productList",all);
    mv.setViewName("product-list");
    return mv;
}

@PreAuthorize(“hasAnyRole(‘ROLE_ADMIN’,‘ROLE_USER’)”)指定多个可用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值