Spring Security 权限管理注解写法

一. 概述

权限是大部分的后台管理系统都需要实现的功能,用户控制不同的角色能够进行的不同的操作。Spring Security的可以进行用户的角色权限控制,也可以进行用户的操作权限控制。

一. 启动类配置

/**
 * 开启方法的注解安全校验。
 *  securedEnabled  @Secured("ROLE_abc")  该注解是Spring security提供的
 *  jsr250Enabled  @RolesAllowed("admin")  该注解是 JSR250 支持的注解形式
 *  prePostEnabled @PreAuthorize("hasAuthority('user:add')
 */
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
public class SecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }
}

二. 基于角色的权限控制

  1. @RoleAllowed
    @RoleAllowed在查询用户的权限的时候,构建角色的时候必须是 ROLE_admin
    使用的时候可以:@RoleAllowed("admin") 或者 @RoleAllowed("ROLE_admin")
  2. @Secured
    @Secured 在查询用户的权限的时候,构建的时候必须是 ROLE_admin
    使用的时候只能是 @Secured({"ROLE_admin"})
  3. @PreAuthorize
    @PreAuthorize构建的时候必须是 ROLE_admin, ROLE_system
    使用的时候只能是 @PreAuthorize("hasRole('ROLE_admin') or|and hasRole('ROLE_system')")
    @PreAuthorize("hasRole('admin')")

三. 基于操作的权限控制

在构建操作权限的时候的时候不需要任何的前缀。例如:user:list user:add
在使用 @PreAuthorize的时候,形式是:@PreAuthorize("hasAuthority('user:list')")

你可能感兴趣的:(Spring Security 权限管理注解写法)