Core1.1遵循了@blowdart的建议,并实现了一个自定义中间件:
https://stackoverflow.com/a/31465227/29821
它是这样工作的:
运行了
这在一定程度上适用于2.0,但如果令牌无效(上面的步骤2)并且从未添加声明,我会得到“没有指定authenticationScheme,并且没有找到DefaultChallengeScheme”。
所以现在我读到身份验证在2.0中发生了变化:
https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
对于我来说,在ASP.NET Core2.0中做同样的事情的正确途径是什么?我没有看到一个真正的自定义身份验证的示例。
发布于 2017-09-08 22:14:40
因此,经过一天的努力解决这个问题,我终于想出了微软希望我们如何为他们在核心2.0中新的单一中间件设置制作自定义身份验证处理程序。
在阅读了一些关于MSDN的文档之后,我发现了一个实现IAuthenticationHandler
接口的名为AuthenticationHandler<TOption>
的类。
在那里,我找到了一个包含现有身份验证方案的完整代码库,位于https://github.com/aspnet/Security
在其中一篇文章中,它展示了微软如何实现JwtBearer身份验证方案。(https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer)
我将大部分代码复制到一个新文件夹中,并清除了所有与JwtBearer
有关的内容。
在JwtBearerHandler
类(扩展AuthenticationHandler<>
)中,有一个对Task<AuthenticateResult> HandleAuthenticateAsync()
的覆盖
我添加了用于通过自定义令牌服务器设置声明的旧中间件,但仍然遇到一些权限问题,当令牌无效且未设置声明时,只是输出200 OK
而不是401 Unauthorized
。
我意识到我已经覆盖了Task HandleChallengeAsync(AuthenticationProperties properties)
,无论出于什么原因,它都是通过控制器中的[Authorize(Roles="")]
来设置权限的。
删除此覆盖后,代码可以正常工作,并在权限不匹配时成功抛出401
。
由此得出的主要结论是,现在您不能使用自定义中间件,必须通过AuthenticationHandler<>
实现它,并且在使用services.AddAuthentication(...)
时必须设置DefaultAuthenticateScheme
和DefaultChallengeScheme
。
下面是一个示例,说明了这一切应该是什么样子:
在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();
}
}
发布于 2017-08-28 21:54:55
正如您参考的文章所指出的,从核心1.x到核心2.0,身份有相当大的变化。主要的变化是摆脱了中间件方法,并使用依赖注入来配置自定义服务。这在为更复杂的实现定制身份时提供了更大的灵活性。因此,您希望摆脱上面提到的中间件方法,转向服务。按照参考文章中的迁移步骤来实现此目标。首先用app.UseAuthentication替换app.UseIdentity。UseIdentity已折旧,未来版本将不再支持。有关如何插入自定义claims转换并在claim view this blog post上执行授权的完整示例。
https://stackoverflow.com/questions/45805411
复制相似问题