您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

在其中一个内部,它显示了Microsoft如何实现JwtBearer身份验证方案。(https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer

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

JwtBearerHandler该类(扩展为AuthenticationHandler<>)中,有一个替代Task<AuthenticateResult> HandleAuthenticateAsync()

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

我意识到我已经重写了Task HandleChallengeAsync(AuthenticationProperties properties),无论出于何种原因,它都用于通过[Authorize(Roles="")]控制器设置权限。

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

这样做的主要好处是,现在您不能使用自定义中间件,必须通过实现它,AuthenticationHandler<>并且必须在使用时设置DefaultAuthenticateScheme和。DefaultChallengeScheme``services.AddAuthentication(...)

这是所有示例的示例:

在Startup.cs / ConfigureServices()中添加

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()中添加

app.UseAuthentication();

创建一个文件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

public class CustomAuthOptions: AuthenticationSchemeOptions
{
    public CustomAuthOptions()
    {

    }
}

创建一个文件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();
    }
}
dotnet 2022/1/1 18:20:22 有597人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶