【问题标题】:Multiple authentication schemes in ASP.NET CoreASP.NET Core 中的多种身份验证方案
【发布时间】:2019-08-31 01:03:53
【问题描述】:

在 ASP.NET Core 1 中,身份验证将在其配置中手动挂接到请求管道中:对于自定义身份验证过程,您只需定义一个 AuthenticationMiddleware 并将其挂接到您的管道中的身份验证点应该会发生。

在 ASP.NET Core 2 中,没有更多的 AuthenticationMiddleware 并且您应该在管道中的某个点执行UseAuthentication()所有身份验证必须发生。

此处记录了差异:https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme

为了区分不同的身份验证方式,有一些由魔术字符串标识的策略(ASP.NET Core 中有很多魔术字符串)。

然后我被告知我可以在我的控制器上选择具有属性的所需方案,但在相关场景中我根本不使用 MVC。那么如何为管道的特定分支指定:

    app.UseWhen(c => ..., app2 =>
    {
        // auth number 1 desired

        ...
    });

    app.UseWhen(c => ..., app2 =>
    {
        // auth number 2 desired

        ...
    });

即使在 MVC 中,身份验证发生在路由之前,那么如何在管道中的 UseAuthentication() 点获得使用哪种方案的信息?

【问题讨论】:

  • 你能提供更多关于你想在你的中间件中做什么的细节吗?例如如果用户未通过身份验证,则返回 401 等?
  • @KirkLarkin 它只是读取标题并在身份验证失败时返回 403。

标签: c# asp.net-core asp.net-core-2.0


【解决方案1】:

您可以通过调用AuthenticateAsync 使用命令式方法来定位特定的身份验证方案。这是一个例子:

app2.Use(async (ctx, next) =>
{
    var authenticateResult = await ctx.AuthenticateAsync("SchemeName");

    if (!authenticateResult.Succeeded)
    {
        ctx.Response.StatusCode = 401; // e.g.
        return;
    }

    // ...
});

AuthenticateAsync 将 authentication-scheme 作为参数,返回一个AuthenticateResult 的实例,通过Succeeded 指示成功或失败,并通过Principal 提供经过身份验证的ClaimsPrincipal

您还可以使用IAuthorizationService 对特定策略执行授权。这是一个示例,说明来自AuthenticateResultPrincipal 如何通过AuthorizeAsync 传递:

var authorizationService = ctx.RequestServices.GetService<IAuthorizationService>();
var authorizationResult = await authorizationService.AuthorizeAsync(
    authenticateResult.Principal, "PolicyName");

if (!authorizationResult.Succeeded)
{
    ctx.Response.StatusCode = 403; // e.g.
    return;
}

// ...

AuthenticateResult 一样,AuthorizationResult 通过Succeeded 指示成功或失败 - 它还提供有关通过Failure 授权失败的原因的信息。

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2022-07-27
    • 2018-02-23
    • 2019-06-13
    • 2018-03-23
    • 2019-07-10
    • 2021-10-18
    • 2017-10-03
    相关资源
    最近更新 更多