栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
401Unauthorized

我意识到我已经重写了

Task HandleChallengeAsync(AuthenticationPropertiesproperties)
,无论出于何种原因,它都用于通过
[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, UrlEnprer enprer, ISystemClock clock) : base(options, logger, enprer, 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();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432957.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号