spring security权限控制

spring security权限控制

SpringSecurity可以通过注解的方式来控制类或者方法的访问权限。注解需要开启对应的注解支持,若注解放在controller类中,对应注解支持应该放在mvc配置文件中,因为controller类是有mvc配置文件扫描并创建的,同理,注解放在service类中,对应注解支持应该放在spring配置文件中。

开启注解支持

<!-- 开启权限控制注解支持 
jsr250-annotations="enabled"表示支持jsr250-api的注解,需要jsr250-api的jar包 
pre-post-annotations="enabled"表示支持spring表达式注解 
secured-annotations="enabled"这才是SpringSecurity提供的注解 -->
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled"/>

在注解支持对应类或者方法上添加注解,eg:

//表示当前类中所有方法都需要ROLE_ADMIN或者ROLE_PRODUCT才能访问 
@Controller 
@RequestMapping("/product") 
@RolesAllowed({"ROLE_ADMIN","ROLE_PRODUCT"})//JSR-250注解
public class ProductController { 
    @RequestMapping("/findAll") 
    public String findAll(){ 
        return "product-list"; 
    } 
}

//表示当前类中findAll方法需要ROLE_ADMIN或者ROLE_PRODUCT才能访问 
@Controller 
@RequestMapping("/product") 
public class ProductController {
    @RequestMapping("/findAll")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_PRODUCT')")//spring表达式注解 
    public String findAll(){ 
        return "product-list";
    } 
}

//表示当前类中所有方法都需要ROLE_ADMIN或者ROLE_PRODUCT才能访问
@Controller 
@RequestMapping("/product")
@Secured({"ROLE_ADMIN","ROLE_PRODUCT"})//SpringSecurity注解 
public class ProductController {
    @RequestMapping("/findAll") 
    public String findAll(){ 
        return "product-list"; 
    } 
}
记得快乐
原文地址:https://www.cnblogs.com/Y-wee/p/14441568.html