ASP.NET Core 2.0身份验证中间件
使用Core 1.1遵循@blowdart的建议并实现了自定义中间件:
With Core 1.1 followed @blowdart's advice and implemented a custom middleware:
https://stackoverflow.com/a/31465227/29821
它是这样工作的:
- 中间件已运行.从请求标头中提取一个令牌.
- 验证令牌,如果有效,则建立包含多个声明的身份(ClaimsIdentity),然后通过HttpContext.User.AddIdentity(); 添加
- 在使用services.AddAuthorization的ConfigureServices中,我添加了一个策略来要求由中间件提供的声明.
- 然后在控制器/动作中,使用[Authorize(Roles =中间件添加的某些角色"))
这在2.0上可以正常工作,除了如果令牌无效(上面的步骤2)并且从不添加声明,我将得到未指定authenticationScheme,并且未找到DefaultChallengeScheme."
This somewhat works with 2.0, except that if the token is not valid (step 2 above) and the claim is never added I get "No authenticationScheme was specified, and there was no DefaultChallengeScheme found."
所以现在我正在阅读auth在2.0中更改了:
So now I'm reading that auth changed in 2.0:
https://docs. microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
在ASP.NET Core 2.0中执行相同操作的正确方法是什么?我没有看到进行真正的自定义身份验证的示例.
What's the right path for me to do the same thing in ASP.NET Core 2.0? I don't see an example to do truly custom authentication.
因此,经过一整天的尝试来解决此问题之后,我终于弄清楚了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(...)
时必须设置DefaultAuthenticateScheme
和DefaultChallengeScheme
.
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();
}
}