【问题标题】:Why is Asp.Net Core Authentication Scheme mandatory为什么 Asp.Net Core 身份验证方案是强制性的
【发布时间】:2017-02-09 21:21:13
【问题描述】:

我对在 Asp.Net Core 中似乎是强制性的身份验证方案这一事实感到非常沮丧。 我的目标是构建一个 API,我不想了解有关客户端的任何信息。我已经构建了自定义身份验证和授权,效果很好。我没有使用身份或 cookie。但是,如果没有有效的身份验证方案,我无法返回 403 Forbid 结果,否则会出现以下异常...

System.InvalidOperationException:没有身份验证处理程序 配置为处理方案:自动

我的问题是,我可以将 MVC 配置为不使用身份验证方案或创建身份验证方案而不依赖登录路径或任何相关路径吗?

【问题讨论】:

  • 请发布一些代码,以便我们帮助您解决问题。
  • @Brad 这更像是一个架构问题。没有我遇到问题的特定代码。基本上,如果您使用 Authorize 属性或大多数处理 User.Identity 的东西,则需要某种身份验证方案。

标签: c# asp.net-mvc security authentication asp.net-core


【解决方案1】:

在仔细研究了 Asp.net Core 安全源代码之后,我设法创建了一个自定义身份验证处理程序。为此,您需要实现 3 个类。

第一个类实现了一个抽象的 AuthenticationOptions。

public class AwesomeAuthenticationOptions : AuthenticationOptions {
    public AwesomeAuthenticationOptions() {
        AuthenticationScheme = "AwesomeAuthentication";
        AutomaticAuthenticate = false;
    }
}

第二个类实现了一个抽象的AuthenticationHandler。

public class AwesomeAuthentication : AuthenticationHandler<AwesomeAuthenticationOptions>
{
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var prop = new AuthenticationProperties();
        var ticket = new AuthenticationTicket(Context.User, prop, "AwesomeAuthentication");
        //this is where you setup the ClaimsPrincipal
        //if auth fails, return AuthenticateResult.Fail("reason for failure");
        return await Task.Run(() => AuthenticateResult.Success(ticket));
    }
}

第三个类实现了一个抽象的AuthenticationMiddleware。

public class AwesomeAuthenticationMiddleware : AuthenticationMiddleware<AwesomeAuthenticationOptions>
{
    public AwesomeAuthenticationMiddleware(RequestDelegate next, 
        IOptions<AwesomeAuthenticationOptions> options,
        ILoggerFactory loggerFactory,
        UrlEncoder urlEncoder) : base(next, options, loggerFactory, urlEncoder) {

    }

    protected override AuthenticationHandler<AwesomeAuthenticationOptions> CreateHandler()
    {
        return new AwesomeAuthentication();
    }
}

最后,在 Startup.cs 的 Configure 方法中使用中间件组件。

app.UseMiddleware<AwesomeAuthenticationMiddleware>();

现在您可以构建自己的身份验证方案。

【讨论】:

  • 您不需要也不应该返回 Task.Run()。务必返回 AuthenticateResult.Success(ticket);而是。
  • 通常如果您没有其他身份验证中间件 Context.User 将成为匿名用户。身份验证处理程序的全部意义在于设置所有内容以填充 Context.User。在 HandleAuthenticateAsync() 中使用它很容易失败。
  • @blowdart 我已经更正了 Task.Run() 的返回。我知道这样做的目的是设置主体,但我在此处添加了此代码作为大纲。
  • 另外,当我使用属性 [Authorize("PolicyName")] 并且使用未经过身份验证时,我收到 403。此时我期待 401。知道为什么吗?
  • 感谢您的反馈。这很棘手,但我想我已经掌握了窍门。一旦我正确实现了 AuthenticationHandler,一切都开始按预期工作。我不必重写未经授权和禁止的处理程序,因为他们做了我想要的。返回 AuthenticateResult.Fail("reason");是什么将主体上的 IsAuthenticated 设置为 false,然后在质询时返回 401。
猜你喜欢
  • 2020-10-29
  • 2018-02-23
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多