在服务器端我们可以通过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’)”)指定多个可用