因此,试图解决这个问题,经过漫长的一天,我终于想通了,微软希望我们如何让自定义验证处理程序在核心2.0新单曲的中间件的设置。
通过一些MSDN上的文档寻找后,我发现了一个名为AuthenticationHandler<TOption>
类,它实现了IAuthenticationHandler
接口。
从那里,我发现了位于https://github.com/aspnet/Security
里面的其中之一的现有认证方案的整个代码库,它显示了微软是如何实现JwtBearer认证方案。 (https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer)
我将大部分代码复制到一个新文件夹中,并清除了所有与JwtBearer
有关的事情。
在JwtBearerHandler
类(扩展AuthenticationHandler<>
),有一个为Task<AuthenticateResult> HandleAuthenticateAsync()
我在我们的旧中间件添加了对通过自定义令牌服务器设置要求的覆盖,并且仍然遇到一些问题的权限,只是随地吐痰如果令牌无效并且没有设置索赔,则输出200 OK
而不是401 Unauthorized
。
我意识到我已经重写了Task HandleChallengeAsync(AuthenticationProperties properties)
,无论什么原因,它都是通过控制器中的[Authorize(Roles="")]
来设置权限。
删除此重写后,代码已经工作,并且在权限不匹配时已成功抛出401
。
从这个主要的外卖是,现在你不能使用自定义的中间件,你必须通过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 /配置()地址:
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();
}
}
试试这个链接,即使它说,2种方案,但它将给ü上的身份验证HTTPS对决://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2 –
您可以添加您的代码,以便我们可以看看吗?我知道我在core2.0的智威汤逊有问题 - 是在启动时移动它的一个案例 – Webezine