本文將介紹如何通過?Sang.AspNetCore.RoleBasedAuthorization[1]?庫實現 RBAC 權限管理。
使用介紹
Step 1
添加庫?Sang.AspNetCore.RoleBasedAuthorization
Install-Package Sang.AspNetCore.RoleBasedAuthorization
Step 2
在?Program.cs
?中添加
builder.Services.AddSangRoleBasedAuthorization();
Step 3
在需要進行授權檢查的接口或 Controller 處添加 ResourceAttribute 標記。
[Resource("資源")]
[Route("api/[controller]")]
[ApiController]
public class RolesController : ControllerBase
{
}
/// <summary>
/// 刪除-數值
/// </summary>
/// <param name="id"></param>
[Resource("刪除-數值")] //[Resource("刪除", Action = "數值")]
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{return Ok("刪除-數值");
}
這里用于描述訪問的角色需要的資源要求
?填寫單獨的整個資源 “[Resource("資源")]”?或使用 Action 設置資源下的某個操作 “[Resource("資源", Action = "操作")]”?也可以使用形如“[Resource("資源-操作")]”直接設置資源和操作
Step 4
完成以上操作后,授權檢查,將檢查User.Claims
是否存在對應的Permission
。
需要為用戶添加對應的?Claims
?,可以在生成 jwt token 時直接包含。
當然也可以使用中間件讀取對應的角色,在授權檢查前添加,可以自己實現也可以使用該庫提供的下一節介紹的功能。
var claims = new List<Claim>
{new Claim(ClaimTypes.NameIdentifier, "uid"),new Claim(ClaimTypes.Name,"用戶名"),new Claim(ClaimTypes.Email,"test@exp.com"),new Claim(ClaimTypes.Role, "user"),new Claim(ResourceClaimTypes.Permission,"查詢"),
};
var token = new JwtSecurityToken("Issuer","Audience",claims,expires: DateTime.UtcNow.AddSeconds(3600),signingCredentials: credentials);
注意:如果角色名為
SangRBAC_Administrator
,將不進行授權檢查。
可選中間件
使用提供的添加角色權限中間件,你也可以單獨使用該組件。
Step 1
實現IRolePermission
,通過角色名獲取該角色權限列表
public class MyRolePermission : IRolePermission
{public Task<List<Claim>> GetRolePermissionClaimsByName(string roleName){List<Claim> list = new();// you codereturn Task.FromResult(list);}
}
然后添加服務。
builder.Services.AddRolePermission<MyRolePermission>();
Step 2
在app.UseAuthorization();
前app.UseAuthentication()
后啟用這個中間件。
app.UseAuthentication();
app.UseRolePermission();
app.UseAuthorization();
Option
UseRolePermission
1. option.UserAdministratorRoleName:
設置一個自定義角色,使其擁有?SangRBAC_Administrator
?一樣的系統內置超級管理員權限。
2. option.Always:
是否一直檢查并執行添加,默認只有在含有?ResourceAttribute
?要進行權限驗證時,此次訪問中間件才啟動添加權限功能。
app.UseRolePermission(opt => {// 設置系統內置超級管理員的rolenameopt.userAdministratorRoleName = "supadmin";option.Always = true;
});
Demo
?簡單示例 https://github.com/sangyuxiaowu/Sang.AspNetCore.RoleBasedAuthorization/tree/main/TestDemo?在 Identity 中使用 https://github.com/sangyuxiaowu/IdentityRBAC
References
[1]
?Sang.AspNetCore.RoleBasedAuthorization:?https://www.nuget.org/packages/Sang.AspNetCore.RoleBasedAuthorization