目录

  • 开发任务
  • 代码实现

开发任务

  • DotNetNB.Security.Core:定义 core,models,Istore;实现 default memory store
  • DotNetNB.Security.ActionAccess:扫描 action;添加 action authorize filter;添加集成方式

代码实现

对于一个 web 项目,Filter 是在构建构建 builder 的时候添加的

builder.Services.AddControllers(options =>
{
options.Filters.Add<>()
})

这里不可能让用户手动添加,所以需要有一个扩展方法给用户调用

using Microsoft.AspNetCore.Mvc;

namespace DotNetNB.Security.ActionAccess
{
public static class MvcOptionsExtensions
{
public static MvcOptions AddActionAccessControl(this MvcOptions options)
{
options.Filters.Add<DynamicAuthorizeFilter>();
return options;
}
}
}

创建 Resource,包含 Key 和 Data 两个属性

namespace DotNetNB.Security.Core.Models
{
public class Resource
{
public string Key { get; set; } public object Data { get; set; }
}
}

创建 ActionResource,继承 Resource,包含 ControllerName,ActionName,RouteTemplate 和 HttpVerb 几个属性

using DotNetNB.Security.Core.Models;

namespace DotNetNB.Security.ActionAccess
{
public class ActionResource : Resource
{ } public class ActionResourceData
{
public string? ControllerName { get; set; } public string? ActionName { get; set; } public string DisplayName { get; set; } public string? RouteTemplate { get; set; } public string? HttpVerb { get; set; }
}
}

定义一个 IResourceManager 接口,提供创建资源的方法

using DotNetNB.Security.Core.Models;

namespace DotNetNB.Security.Core
{
public interface IResourceManager
{
public Task CreateAsync(Resource resource); public Task CreateAsync(IEnumerable<Resource> resources);
}
}

参考 ASP .NET Core 源码中的 ActionEndpointDataSourceBase:

https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Routing/ActionEndpointDataSourceBase.cs

创建 endpoint 的时候有一个 action 的列表 ActionDescriptors

var endpoints = CreateEndpoints(_actions.ActionDescriptors.Items, Conventions);

它的类型是一个 IActionDescriptorCollectionProvider,专门用于扫描获取所有的 action

private readonly IActionDescriptorCollectionProvider _actions;

在 ActionAccess 模块的 ActionResourceProvider 中把它加进来

using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace DotNetNB.Security.ActionAccess
{
public class ActionResourceProvider
{
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; public ActionResourceProvider(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
}
}

在 host 启动的时候扫描获取所有的 action 信息,定义一个 IResourceProvider 接口

namespace DotNetNB.Security.Core
{
public interface IResourceProvider
{
public Task<IEnumerable<Resource>> ExecuteAsync();
}
}

ActionResourceProvider 实现这个接口,从 ActionDescriptors 获取 action 信息,构建 ActionResourceData

public async Task<IEnumerable<Resource>> ExecuteAsync()
{
var actions = _actionDescriptorCollectionProvider.ActionDescriptors.Items;
var actionResources = new List<ActionResource>(); foreach (var action in actions)
{
if (action is ControllerActionDescriptor)
{
var actionDescriptor = action as ControllerActionDescriptor;
var httpMethod = action.EndpointMetadata.Where(m => m is HttpMethodMetadata).FirstOrDefault() as HttpMethodMetadata; var routeAttribute =
actionDescriptor?.EndpointMetadata.FirstOrDefault(m => m is RouteAttribute) as RouteAttribute; var resourceData = new ActionResourceData();
resourceData.HttpVerb = httpMethod?.HttpMethods.First();
resourceData.ActionName = actionDescriptor?.ActionName;
resourceData.ControllerName = actionDescriptor?.ControllerName;
resourceData.RouteTemplate = routeAttribute?.Template;
resourceData.DisplayName = action.DisplayName; actionResources.Add(new ActionResource()
{
Data = resourceData,
Key = actionDescriptor.GetSecurityKey()
});
}
} return await Task.FromResult(actionResources);
}

参考 ASP .NET Core 源码中的 AuthorizeFilter:

https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs

AuthorizeFilter 中有一个 OnAuthorizationAsync 的方法,首先获取 policy 执行器,然后执行了认证,接着执行授权,根据授权结果修改 AuthorizationFilterContext,我们权限主要是 Forbidden 的结果,返回 403 即可

public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
} if (!context.IsEffectivePolicy(this))
{
return;
} // IMPORTANT: Changes to authorization logic should be mirrored in security's AuthorizationMiddleware
var effectivePolicy = await GetEffectivePolicyAsync(context);
if (effectivePolicy == null)
{
return;
} var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService<IPolicyEvaluator>(); var authenticateResult = await policyEvaluator.AuthenticateAsync(effectivePolicy, context.HttpContext); // Allow Anonymous skips all authorization
if (HasAllowAnonymous(context))
{
return;
} var authorizeResult = await policyEvaluator.AuthorizeAsync(effectivePolicy, authenticateResult, context.HttpContext, context); if (authorizeResult.Challenged)
{
context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
}
else if (authorizeResult.Forbidden)
{
context.Result = new ForbidResult(effectivePolicy.AuthenticationSchemes.ToArray());
}
}

DynamicAuthorizeFilter 继承自 AuthorizeFilter,只获取 ControllerActionDescriptor 类型的 action,如果 permissions 中不包含 actionKey 则返回 403

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters; namespace DotNetNB.Security.ActionAccess
{
public class DynamicAuthorizeFilter : AuthorizeFilter
{
public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (actionDescriptor == null)
{
return;
} base.OnAuthorizationAsync(context);
if (context.Result != null)
{
return;
} var permissions = context.HttpContext.User.Claims.Where(c => c.Type == Core.ClaimsTypes.Permission);
var actionKey = actionDescriptor.GetSecurityKey(); var values = permissions.Select(p => p.Value);
if (!values.Contains(actionKey))
{
context.Result = new ForbidResult();
}
}
}
}

在 ClaimsTypes 中增加一个 Permission 类型的 ClaimsType

namespace DotNetNB.Security.Core
{
public static class ClaimsTypes
{
public const string Permission = "Permission";
}
}

为了避免重复代码,添加一个 GetSecurityKey 的扩展方法

using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Internal; namespace DotNetNB.Security.ActionAccess; public static string GetSecurityKey(this ControllerActionDescriptor descriptor)
{
var httpMethod = descriptor.EndpointMetadata.FirstOrDefault(m => m is HttpMethodMetadata) as HttpMethodMetadata; return string.Format($"{descriptor?.ControllerName}-{descriptor?.ActionName}-{httpMethod.HttpMethods.First()}");
}

这样就完成了 DotNetNB.Security.ActionAccess 模块的 ActionResourceProvider 和 DynamicAuthorizeFilter

GitHub源码链接:

https://github.com/MingsonZheng/dotnetnb.security

课程链接

https://appsqsyiqlk5791.h5.xiaoeknow.com/v1/course/video/v_5f39bdb8e4b01187873136cf?type=2

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

.NET 云原生架构师训练营(权限系统 代码实现 ActionAccess)--学习笔记的更多相关文章

  1. .NET 云原生架构师训练营(建立系统观)--学习笔记

    目录 目标 ASP .NET Core 什么是系统 什么是系统思维 系统分解 什么是复杂系统 作业 目标 通过整体定义去认识系统 通过分解去简化对系统的认识 ASP .NET Core ASP .NE ...

  2. .NET 云原生架构师训练营(对象过程建模)--学习笔记

    目录 UML OPM OPM优化 UML 1997年发布UML标准 主要域 视图 图 主要概念 结构 静态视图 类图 类.关联.泛化.依赖关系.实现.接口 用例视图 用例图 用例.参与者.关联.扩展. ...

  3. .NET 云原生架构师训练营(设计原则&&设计模式)--学习笔记

    目录 设计原则 设计模式 设计原则 DRY (Don't repeat yourself 不要重复) KISS (Keep it stupid simple 简单到傻子都能看懂) YAGNI (You ...

  4. .NET 云原生架构师训练营(责任链模式)--学习笔记

    目录 责任链模式 源码 责任链模式 职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无需关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了 何时使用:在处理 ...

  5. .NET 云原生架构师训练营(系统架构)--学习笔记

    目录 对外展现的功能 内部功能 功能交互与价值通路 系统架构 目标 认识系统的价值通路 认识功能架构,通过把功能结构与形式结构结合来描述系统架构 受益原则 好的架构必须使人受益,要想把架构做好,就要专 ...

  6. .NET 云原生架构师训练营(模块一 架构师与云原生)--学习笔记

    目录 什么是软件架构 软件架构的基本思路 单体向分布式演进.云原生.技术中台 1.1 什么是软件架构 1.1.1 什么是架构? Software architecture = {Elements, F ...

  7. .NET 云原生架构师训练营(权限系统 RGCA 架构设计)--学习笔记

    目录 项目核心内容 实战目标 RGCA 四步架构法 项目核心内容 无代码埋点实现对所有 API Action 访问控制管理 对 EF Core 实体新增.删除.字段级读写控制管理 与 Identity ...

  8. .NET 云原生架构师训练营(权限系统 RGCA 开发任务)--学习笔记

    目录 目标 模块拆分 OPM 开发任务 目标 基于上一讲的模块划分做一个任务拆解,根据任务拆解实现功能 模块拆分 模块划分已经完成了边界的划分,边界内外职责清晰 OPM 根据模块拆分画出 OPM(Ob ...

  9. .NET 云原生架构师训练营(权限系统 代码实现 Identity)--学习笔记

    目录 开发任务 代码实现 开发任务 DotNetNB.Security.Core:定义 core,models,Istore:实现 default memory store DotNetNB.Secu ...

随机推荐

  1. 初识python: 继承

    继承:可以使用现有类的所有功能,并在无需重新编写原来的类的情况下对这些功能进行扩展. 通过继承创建的新类称为"子类"或"派生类". 被继承的类称为"基 ...

  2. jsp文件中文乱码解决

    文件顶加上 <%@ page contentType="text/html;charset=UTF-8" language="java" %>即可

  3. 2022年form表单中input控件最详细总结

    语法 <input type="" name="" id="" value="" placeholder=&quo ...

  4. RocketMQ 原理:消息存储、高可用、消息重试、消息幂等性

    目录 消息存储 消息存储方式 非持久化 持久化 消息存储介质 消息存储与读写方式 消息存储结构 刷盘机制 同步刷盘 异步刷盘 小结 高可用 高可用实现 主从复制 负载均衡 消息重试 顺序消息重试 无序 ...

  5. git 重置密码后,本地电脑需要修改git密码

    查看用户名git config user.name 查看密码git config user.password 查看邮箱git config user.email 修改密码git config --gl ...

  6. manjaro20夜灯夜间模式开关

  7. ROS之arduino交互

    一.第一种安装方式(不支持自定义消息) 第一步打开官网 http://wiki.ros.org/rosserial_arduino/Tutorials/Arduino%20IDE%20Setup 第二 ...

  8. Sentry 开发者贡献指南 - 浏览器 SDK 集成测试

    Sentry 的浏览器 SDK 的集成测试在内部使用 Playwright.这些测试在 Chromium.Firefox 和 Webkit 的最新稳定版本上运行. https://playwright ...

  9. 集合框架-TreeSet-Comparator比较器练习(字符串长度排序)

    1 package cn.itcast.p5.treeset.test; 2 3 import java.util.Iterator; 4 import java.util.TreeSet; 5 6 ...

  10. css中设置背景图片适应屏幕

    以body为例 body{ background: url(../img/jld.png) no-repeat center center fixed; -webkit-background-size ...