Framework
Hope 实现Authentication & Authorization, JWT, RBAC
要检查登录账户的权限,您需要三个步骤:
检查 Milestone 20240510 rbac
部分:
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"}];
}
hope-wire.json
配置 2. 添加枚举到 "authority" : {
"enumClass" : "com.novel.book.proto.infra.settings.BookAuthorityEnum",
"codePrefix" : 10240000
}
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
}
}
};
}
这些配置将在您的应用程序模块中进行,而不是在proto模块中:
在您的应用程序项目的包中找到自动生成的代码模板:${PKG}.infra.security
(以Book
为例,域为Book
):
1. AnonymousBookCustomer.java
2. BookCustomer.java
3. BookJWTPicker.java
4. BookQuickCustomerRoleChecker.java
5. BookSecurityCustomerContextCustomizer.java
6. BookSecurityCustomizer.java
Class | Usage | Comment |
---|---|---|
AnonymousBook Customer | 匿名顾客定义 | 通常无需更新 |
Book Customer | 在安全上下文中使用的顾客 | 扩展以便动态加载附加字段,如权限,通常是Book SecurityCustomerContextCustomizer的响应,用于初始化并进行包装,需扩展 |
Book JWTPicker | 获取JWT的位置 | 通常从头部获取,但也可以从会话或cookies中获取 |
Book QuickCustomerRoleChecker | 快速平台/租户角色检查器 | 通常需要扩展 |
Book SecurityCustomerContextCustomizer | 安全上下文顾客初始化的响应 | 从token获取更多详细信息,创建新的顾客,如委托权限/角色获取器 |
Book SecurityCustomizer | 安全配置定制 | 更改全局安全策略:如默认访问检查,或特定路径的特定规则 |
这不是框架所能提供的,因为这依赖于您的业务逻辑:如何设置您与权限列表的账户关系。
最佳实践是遵循基于角色的访问控制,即 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!