From 67c567eb2c19beac2355269e7a0562195d3f86fe Mon Sep 17 00:00:00 2001 From: hello Date: Wed, 27 Mar 2024 14:50:53 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=88=E6=9D=83=E7=B3=BB=E7=BB=9F=E8=AE=BE?= =?UTF-8?q?=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/authorization.md | 84 -------------------------------- 1 file changed, 84 deletions(-) diff --git a/notes/helloshop/authorization.md b/notes/helloshop/authorization.md index dbf57ce..a69cbf8 100644 --- a/notes/helloshop/authorization.md +++ b/notes/helloshop/authorization.md @@ -2,90 +2,6 @@ 身份认证完成后 HttpContext.User 中包含了用户的身份信息,但是用户的身份信息并不包含用户的权限信息。用户的权限信息需要通过授权系统来获取。 -## 授权三要素 - -授权系统的核心是授权三要素:授权主体、授权策略、资源。授权主体是指需要进行授权的对象,可以是用户,也可以是角色,也可以是组织机构。授权策略是指授权的规则,可以是基于角色的授权策略,也可以是基于资源的授权策略。资源是指需要授权的对象,可以是数据,也可以是服务。 - -例如:张三(授权主体)有订单001(资源)的查看权限(授权策略),管理员(授权主体)有所有订单(资源)的管理权限(授权策略)。 - -资源更细粒度的描述:资源类型、资源标识、资源属性。 - -例如:张三(授权主体)有订单001的金额和支付时间(资源)的查看权限(授权策略) - -值得一说的是组织结构,部门,第三方系统,等其它类型的主体,都可以与某个角色绑定,这样就可以实现对某个部门的权限控制。 - - -## 常见的权限控制模型 - -常见的权限控制模型有:DAC(Discretionary Access Control)、MAC(Mandatory Access Control)、RBAC(Role-Based Access Control)、ABAC(Attribute-Based Access Control)。 - -## 基于角色的访问控制 - -基于角色的访问控制是指通过角色来控制用户对资源的访问权限。角色是一组权限的集合,用户通过分配角色来获取相应的权限。基于角色的访问控制模型简单易用,但是角色的管理和权限的分配比较复杂。 - -## 权限 ACL 存储设计 - -```csharp -public class PermissionGranted -{ - public int Id { get; set; } - - public int RoleId { get; set; } - - public required string PermissionName { get; set; } - - public string? ResourceType { get; set; } - - public string? ResourceId { get; set; } -} -``` - -## 在 DbContext 中配置 ACL 实体 - -```csharp -public void Configure(EntityTypeBuilder builder) -{ - builder.ToTable("PermissionGranted"); - - builder.Property(x => x.Id); - builder.Property(x => x.PermissionName).HasMaxLength(64); - builder.Property(x => x.ResourceType).HasMaxLength(16); - builder.Property(x => x.ResourceId).HasMaxLength(32); - - builder.HasOne().WithMany().HasForeignKey(x => x.RoleId).IsRequired(); - - builder.HasIndex(x => new { x.RoleId, x.PermissionName, x.ResourceType, x.ResourceId }).IsUnique(); -} - -``` - -## 设计一个权限检查器 - -```csharp -public interface IPermissionChecker -{ - Task IsGrantedAsync(string name, string? resourceType = null, string? resourceId = null); - - Task IsGrantedAsync(ClaimsPrincipal claimsPrincipal, string name, string? resourceType = null, string? resourceId = null); -} -``` - -## 实现权限检查器 - - -![permission-checker](https://oss.xcode.me/notes/helloshop/permission-checker.svg) - -```csharp -public class RemotePermissionChecker: IPermissionChecker - -public class LocalPermissionChecker: IPermissionChecker -``` - -## 实现权限检查器 - -使用 DbContext 实现本地权限检查器,使用 HttpClient 实现远程权限检查器。 ->>>>>>> 77a8ea98c7f1845343577d0a1e16b164f5d33b4c - ## ASP.NET Core 中的授权系统 ASP.NET Core 中的授权系统是基于策略的授权系统,可以通过声明式的方式来定义授权策略。授权策略可以基于角色,也可以基于资源,也可以基于其他的条件。授权策略可以通过声明式的方式来定义,也可以通过代码的方式来定义。