首页 > 编程语言 > 详细

spring security权限控制

时间:2021-02-24 23:43:47      阅读:27      评论:0      收藏:0      [点我收藏+]

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"; 
    } 
}

spring security权限控制

原文:https://www.cnblogs.com/Y-wee/p/14441568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!