1. Framework
  2. 极简 Authentication & Authorization

Authentication

JWT

Authorization

要检查登录账户的权限,您需要三个步骤:

  1. 定义资源(API路径)的授权属性
  2. 登录账户安全上下文自定义
  3. 设置账户和权限的映射

Define resource authorization

检查 Milestone 20240510 rbac 部分:

domain design

1. 设置权限枚举

enum  BookAuthorityEnum {

    option (hope.swagger.enm) = {
        description: "Authority used in book project"
    };

    BOOK_ADD = 0 [(hope.constant.field) = {code: 1,message: "book:add", message2: "Authority to add book"}];
    BOOK_DELETE = 1 [(hope.constant.field) = {code: 2,message: "book:remove", message2: "Authority to delete book"}];
    BOOK_MODIFY = 2 [(hope.constant.field) = {code: 3,message: "book:modify", message2: "Authority to modify book"}];

}

2. 添加枚举到 hope-wire.json 配置

  "authority" : {
    "enumClass" : "com.novel.book.proto.infra.settings.BookAuthorityEnum",
    "codePrefix" : 10240000
  }

3. 包含你的资源


  rpc ListCategory (com.novel.book.proto.api.admin.request.CategoryListRequest) returns (com.novel.book.proto.api.admin.response.CategoryVoResponse) {
    option (hope.swagger.operation) = {
      get: "/list-category";
      description: "list all the categories support";
      priority: MIDDLE;
      out_plural: true;
      authorization:{
        rbac:{
          authorities: "BOOK_DELETE";
          combinator: OR;
          predefined_role_checker: PLATFORM_MANAGER
        }
      }
    };
  }

4. 运行时配置

这些配置将在您的应用程序模块中进行,而不是在proto模块中:

在您的应用程序项目的包中找到自动生成的代码模板:${PKG}.infra.security(以Book为例,域为Book):

    1. AnonymousBookCustomer.java       
    2. BookCustomer.java                
    3. BookJWTPicker.java               
    4. BookQuickCustomerRoleChecker.java
    5. BookSecurityCustomerContextCustomizer.java
    6. BookSecurityCustomizer.java
ClassUsageComment
AnonymousBookCustomer匿名顾客定义通常无需更新
BookCustomer在安全上下文中使用的顾客扩展以便动态加载附加字段,如权限,通常是BookSecurityCustomerContextCustomizer的响应,用于初始化并进行包装,需扩展
BookJWTPicker获取JWT的位置通常从头部获取,但也可以从会话或cookies中获取
BookQuickCustomerRoleChecker快速平台/租户角色检查器通常需要扩展
BookSecurityCustomerContextCustomizer安全上下文顾客初始化的响应从token获取更多详细信息,创建新的顾客,如委托权限/角色获取器
BookSecurityCustomizer安全配置定制更改全局安全策略:如默认访问检查,或特定路径的特定规则

5. 最后部分

这不是框架所能提供的,因为这依赖于您的业务逻辑:如何设置您与权限列表的账户关系。

最佳实践是遵循基于角色的访问控制,即 RBAC

因此,您可以利用权限枚举,例如 BookAuthorityEnum 的消息模式来组织您的权限层次结构:

以这个书籍应用程序为例:


BOOK_ADD: book:add
BOOK_DELETE: book:delete
USER_BLOCK: user:block
USER_EDIT: user:edit
ORDER_APPROVE:order:approve
ORDER_DELETE:order:delete
ORDER_MODIFY:order:modify

因此,层次结构可能如下所示:


+---book
|       add
|       delete
|
+---user
|       block
|       edit
|
+---order
|       approve
|       delete
|       modify

㊗️ so enjoy!

Reference

  1. RBAC-Wiki