c# - 如何在代码中检查 ASP.NET 身份验证策略而不是使用 AuthorizeAttribute?

标签 c# asp.net-core authorization

在 ASP.NET Core 的授权系统中检查策略是否得到满足的正常方法是在 ConfigureServices 中设置策略,如下所示:

services.AddAuthorization(conf => {
    conf.AddPolicy("UserHasRecentPassport", policy => policy.RequireAssertion(ctx => { return ctx.User.HasRecentPassport(); }));
}

...然后使用 AuthorizeAttribute 为 Controller 或操作指定它,如下所示:

[Authorize("UserHasRecentPassport")]
public class HomeController : Controller {
    public IActionResult Index() {
        return View();
    }
}

但是,我正在编写一个标签助手,它需要检查是否满足特定策略。因此,我只需要在代码中检查这一点,而不是使用 AuthorizeAttribute 方法,即。像这样的东西:

public override void Process(TagHelperContext context, TagHelperOutput output) {
    output.TagName = null;
    if (!policyRequirementIsMet("UserHasRecentPassport")) {
        output.SuppressOutput();
    }
}

我有什么方法可以实现 policyRequirementIsMet 以便它转到 ASP.NET Core 并说“告诉我是否满足名为 X 的策略”?

最佳答案

使用IAuthorizationService执行 imperative authorization .当在 TagHelper 类中使用时,它比文档中显示的要复杂一些,因为它们不能直接访问 HttpContextUser.

这是一种使用 [ViewContext] 的方法属性作为获取 HttpContextUser 的手段,并使用 DI 获取 IAuthorizationService:

public class PassportTagHelper : TagHelper
{
    private readonly IAuthorizationService authorizationService;

    public PassportTagHelper(IAuthorizationService authorizationService)
    {
        this.authorizationService = authorizationService;
    }

    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override async Task ProcessAsync(TagHelperContext ctx,
        TagHelperOutput output)
    {
        var httpContext = ViewContext.HttpContext;
        var authorizationResult = await authorizationService
            .AuthorizeAsync(httpContext.User, "UserHasRecentPassport");

        if (!authorizationResult.Succeeded)
            output.SuppressOutput();
    }
}

注意事项:

  • HttpContext 是通过 ViewContext 属性访问的,该属性是通过使用 [ViewContext] 属性对其进行装饰而设置的。
  • Process 更改为 ProcessAsync,以便我们可以使用 await
  • AuthorizeAsync 返回的值是一个 AuthorizationResult ,它通过其 Succeeded 属性指示成功,并在其 Failure 属性中指示失败的原因。

关于c# - 如何在代码中检查 ASP.NET 身份验证策略而不是使用 AuthorizeAttribute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58484173/

相关文章:

c# - 升级到 .NET Framework 4.8 时出现程序集绑定(bind)问题

asp.net-core - 如何在ASP.NET 5中使用 “old”依赖项

c# - ASP.NET Core MVC 中的 Crystal Reports 错误。无法加载文件

c# - 带有 SAML 2.0 的 WIF(Windows Identity Foundation)

c# - 给定索引和纹理大小的位置,我如何计算我的 hextiles 位置?

c# 将 JSON 日期序列化为 ruby

c# - 如何连接到写在 web 服务的 web.config 中的连接字符串

c# - System.MethodAccessException : 'Attempt by method ' Microsoft. Extensions.Logging.Configuration 问题

c# - Blazor WASM + AAD B2C + 自定义授权

authorization - 根据授权限制维护 View 输出