且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core 2.0身份验证中间件

更新时间:2023-02-16 10:41:37

因此,经过一整天的尝试来解决此问题之后,我终于弄清楚了Microsoft希望我们如何为他们的新单身制造自定义身份验证处理程序,核心2.0中的中间件设置.

So, after a long day of trying to solve this problem, I've finally figured out how Microsoft wants us to make custom authentication handlers for their new single-middleware setup in core 2.0.

浏览了MSDN上的一些文档后,我发现了一个名为AuthenticationHandler<TOption>的类,该类实现了IAuthenticationHandler接口.

After looking through some of the documentation on MSDN, I found a class called AuthenticationHandler<TOption> that implements the IAuthenticationHandler interface.

从那里,我找到了一个完整的代码库,其中包含位于 https://github.com/aspnet的现有身份验证方案. /安全性

From there, I found an entire codebase with the existing authentication schemes located at https://github.com/aspnet/Security

其中之一显示了Microsoft如何实现JwtBearer身份验证方案. ( https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer )

Inside of one of these, it shows how Microsoft implements the JwtBearer authentication scheme. (https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer)

我将大部分代码复制到了一个新文件夹中,并清除了与JwtBearer有关的所有内容.

I copied most of that code over into a new folder, and cleared out all the things having to do with JwtBearer.

JwtBearerHandler类(扩展了AuthenticationHandler<>)中,有一个Task<AuthenticateResult> HandleAuthenticateAsync()

In the JwtBearerHandler class (which extends AuthenticationHandler<>), there's an override for Task<AuthenticateResult> HandleAuthenticateAsync()

我在旧的中间件中添加了通过自定义令牌服务器设置声明的权限,但仍然遇到一些权限问题,当令牌无效且没有声明时,只会吐出200 OK而不是401 Unauthorized.设置.

I added in our old middleware for setting up claims through a custom token server, and was still encountering some issues with permissions, just spitting out a 200 OK instead of a 401 Unauthorized when a token was invalid and no claims were set up.

我意识到我已经覆盖了Task HandleChallengeAsync(AuthenticationProperties properties),无论出于何种原因,该原因都被用来通过控制器中的[Authorize(Roles="")]设置权限.

I realized that I had overridden Task HandleChallengeAsync(AuthenticationProperties properties) which for whatever reason is used to set permissions via [Authorize(Roles="")] in a controller.

删除此替代项后,代码可以正常工作,并且在权限不匹配时成功抛出了401.

After removing this override, the code had worked, and had successfully thrown a 401 when the permissions didn't match up.

主要的收获是,现在您不能使用自定义中间件,必须通过AuthenticationHandler<>实现它,并且在使用services.AddAuthentication(...)时必须设置DefaultAuthenticateSchemeDefaultChallengeScheme.

The main takeaway from this is that now you can't use a custom middleware, you have to implement it via AuthenticationHandler<> and you have to set the DefaultAuthenticateScheme and DefaultChallengeScheme when using services.AddAuthentication(...).

下面是所有示例的示例:

Here's an example of what this should all look like:

在Startup.cs/ConfigureServices()中添加:

In Startup.cs / ConfigureServices() add:

services.AddAuthentication(options =>
{
    // the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
    options.DefaultAuthenticateScheme = "Custom Scheme";
    options.DefaultChallengeScheme = "Custom Scheme";
})
.AddCustomAuth(o => { });

在Startup.cs/Configure()中添加:

In Startup.cs / Configure() add:

app.UseAuthentication();

创建一个新文件CustomAuthExtensions.cs

Create a new file CustomAuthExtensions.cs

public static class CustomAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
    }
}

创建一个新文件CustomAuthOptions.cs

Create a new file CustomAuthOptions.cs

public class CustomAuthOptions: AuthenticationSchemeOptions
{
    public CustomAuthOptions()
    {

    }
}

创建一个新文件CustomAuthHandler.cs

Create a new file CustomAuthHandler.cs

internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
        // store custom services here...
    }
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // build the claims and put them in "Context"; you need to import the Microsoft.AspNetCore.Authentication package
        return AuthenticateResult.NoResult();
    }
}