• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Y-wee
博客园    首页    新随笔    联系   管理     

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"; 
    } 
}
记得快乐
posted @ 2021-02-24 15:10  Y-wee  阅读(382)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3