后端基于方法的权限控制--Spirng-Security
默认情况下, Spring Security 并不启用方法级的安全管控. 启用方法级的管控后, 可以针对不同的方法通过注解设置不同的访问条件;Spring Security 支持三种方法级注解, 分别是 JSR-205/Secured 注解/prePostEnabled。

开启方法级别注解

<global-method-security secured-annotations="enabled" />

<global-method-security jsr250-annotations="enabled" />

<global-method-security pre-post-annotations="enabled" />
//@Secured 注解
@EnableGlobalMethodSecurity(securedEnabled=true)
//JSR-205 注解
@EnableGlobalMethodSecurity(jsr250Enabled=true)
//@PreAuthorize 类型的注解(支持 Spring 表达式)
@EnableGlobalMethodSecurity(prePostEnabled=true)
开始方法级别的注释使用
  1. Secured
    只有满足角色的用户才能访问被注解的方法, 否则将会抛出 AccessDenied 异常.

  2. JSR-205

  3. PreAuthorize
    JSR-205 和 Secured 注解功能较弱, 不支持 Spring EL 表达式. 推荐使用 @PreAuthorize 类型的注解.

详解PreAuthorize表达式
  1. returnObject 保留名
    对于 @PostAuthorize 和 @PostFilter 注解, 可以在表达式中使用 returnObject 保留名, returnObject 代表着被注解方法的返回值, 我们可以使用 returnObject 保留名对注解方法的结果进行验证.
    比如:
@PostAuthorize ("returnObject.owner == authentication.name")
public Book getBook();
  1. 表达式中的 # 号
    在表达式中, 可以使用 #argument123 的形式来代表注解方法中的参数 argument123.
    比如:
@PreAuthorize ("#book.owner == authentication.name")
public void deleteBook(Book book);

还有一种 #argument123 的写法, 即使用 Spring Security @P注解来为方法参数起别名, 然后在 @PreAuthorize 等注解表达式中使用该别名. 不推荐这种写法, 代码可读性较差.

@PreAuthorize("#c.name == authentication.name")
public void doSomething(@P("c") Contact contact);
  1. 内置表达式有:
08-07 09:38