net6授权认证源码详解(一)

发布于:2022-12-16 ⋅ 阅读:(1498) ⋅ 点赞:(1)

认证

首先,先讲认证知识,话不多说,直接进入源码学习查看。

app.UseAuthentication();进入源码,路径(aspnetcore/src/Security/Authentication/Core/src/AuthAppBuilderExtensions.cs)

具体操作:

1、获取IAuthenticationRequestHandle子类Authenticationhandler,调用InitializeAsync初始化,然后调用handleReuestAsync。

2、获取默认AuthenticationScheme(例如下面"Bearer"对应的AuthenticationScheme),然后调用IAuthencticationService.AuthenticateAsync,如果成功,记录User信息。

看完处理代码,我们回过头,看下认证注册代码情况。先以JWT为思路进行查看。

调用代码如下:

builder.Services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options => {
    options.Authority = "http://localhost:5100";
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateAudience = false };
    options.RequireHttpsMetadata = false;
});

看下AddAuthentication("Bearer")注册详情,目的是:设置AuthenticationOptions中DefaultScheme为"Bearer",和AddAuthentication()。路径(aspnetcore/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs)

 继续查看services.AddAuthenticationCore(),路径(aspnetcore/src/Http/Authentication.Core/src/AuthenticationCoreServiceCollectionExtensions.cs)

 这里重点关注两个类,AuthenticationSchemeProvider和AuthenticationHandlerProvider。

AuthenticationSchemeProvider 中用到的操作如下:

1、

GetDefaultAuthenticateSchemeAsync()->GetDefaultSchemeAsync()->GetSchemeAsync("XXX")

这里"XXX"即为代码段"AddAuthentication("Bearer")"中的"Bearer"。GetSchemeAsync的作用是有没有默认值,有则返回"Bearer"对应的AuthenticationScheme,无则返回null。

2、

GetRequestHandlerSchemesAsync()返回AuthenticationScheme中HandlerType继承IAuthenticationRequestHandler的AuthenticationScheme列表。

3、

GetSchemeAsync(_schemes.ContainsKey(name) ? _schemes[name] : null),存在返回AuthenticationScheme,不存在返回null。

AuthenticationHandlerProvider 中用到的操作如下:

 GetHandlerAsync()获取schema的HandleType类型,并且创建实例(JwtBearerHandle),然后调用初始化方法,完成初始化操作。

继续查看services.AddJwtBearer("Bearer",options=>{}),主要是用来对JwtBearerOptions配置项进行配置工作。路径

(aspnetcore/src/Security/Authentication/JwtBearer/src/JwtBearerExtensions.cs)。

下面是具体Services.Configure<AuthenticationOptions>(o=>{})具体配置内容,路径(runtime/src/libraries/Microsoft.Extensions.Options/src/OptionsServiceCollectionExtensions.cs)

配置选项,AuthenticationOptions(内包含Schemes->AuthenticationSchemeBuilder->AuthenticationScheme)。

AddOptions:创建了一个OptionsBuilder对象,然后调用它重载方法Configure<TService...>去创建具有多个泛型的ConfigureNamedOptions对象。

通过services.AddJwtBearer("Bearer",options=>{})中options=>{}对JwtBearerOptions进行配置,并且设置Validate验证规则。JwtBearerHandler配置为name为"Bearer"的AuthenticationScheme的HandlerType。

下一节继续介绍剩余认证内容。。。


网站公告

今日签到

点亮在社区的每一天
去签到