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

编程入门 行业动态 更新时间:2024-10-25 04:21:31
本文介绍了ASP.NET Core 2.0身份验证中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用Core 1.1遵循@blowdart的建议并实现了自定义中间件:

With Core 1.1 followed @blowdart's advice and implemented a custom middleware:

stackoverflow/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:

    docs. microsoft/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.

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

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

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

    Inside of one of these, it shows how Microsoft implements the JwtBearer authentication scheme. (github/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(); } }

    更多推荐

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

    本文发布于:2023-11-05 09:48:35,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1560514.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:身份验证   中间件   NET   ASP   Core

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!