锋翎文档
Java SDKAOP 切面

@PermissionVerify

基于 token scope 的权限验证注解

@PermissionVerify

@PermissionVerify 用于在 Controller 方法执行前校验当前用户权限。 它校验的是 OAuth2 token 自省结果中的 scope 字段。

对应关系(你最关心的)

你写的注解实际校验对象规则
@PermissionVerify(value = {"user:read"})Token 的 scope必须包含 user:read
@PermissionVerify(value = {"a", "b"}, requireAll = true)Token 的 scopeab 都要有
@PermissionVerify(value = {"a", "b"}, requireAll = false)Token 的 scope有任意一个即可

scope 由空格分隔,示例: profile:read profile:write admin

前置条件

  • 请求需要先经过 BeaconSsoFilter
  • Filter 会把 IntrospectResult 放到请求属性 beacon.sso.introspection
  • AOP 切面再读取该属性完成权限判断

如果请求未携带有效 token,会先返回 401;不是 @PermissionVerify 返回 403

注解参数

参数类型默认值说明
valueString[]{}所需权限列表(scope)
requireAllbooleantruetrue=AND, false=OR
messageString"权限不足"校验失败提示

使用示例

@RestController
@RequestMapping("/api/orders")
@PermissionVerify(value = {"order:read"}) // 类级:默认需要 order:read
public class OrderController {

    @GetMapping("/{id}")
    public BaseResponse<String> detail(
            @PathVariable String id,
            @InjectData("sub") String userId) {
        return BaseResponse.success("ok", "user=" + userId + ", id=" + id);
    }

    // 方法级会覆盖类级:改为写权限
    @PostMapping
    @PermissionVerify(value = {"order:write"}, message = "缺少订单写权限")
    public BaseResponse<String> create() {
        return BaseResponse.success("ok", "created");
    }

    // OR 模式:只要有任意一个权限即可
    @DeleteMapping("/{id}")
    @PermissionVerify(value = {"order:delete", "admin"}, requireAll = false)
    public BaseResponse<String> remove(@PathVariable String id) {
        return BaseResponse.success("ok", "deleted:" + id);
    }
}

类级别与方法级别

方法级别 @PermissionVerify 会覆盖类级别定义。

建议把通用权限放类级,把差异权限放方法级覆盖。

失败响应

权限不足时,SDK 返回 403

{
  "code": 403,
  "message": "权限不足",
  "data": null
}

如果设置了 message,响应会返回你自定义的提示文本。

常见问题

问题说明
value 留空会怎样不做权限校验,直接放行
为什么明明有注解却没生效请求可能未经过 BeaconSsoFilter,或 exclude-urls 配置把它排除了
为什么返回 401 而不是 403先发生了认证失败(缺 token / token 无效),还没到权限校验阶段

On this page