前言:本文將會結合asp.net core 認證源碼來分析起認證的原理與流程。asp.net core版本2.2 對於大部分使用asp.net core開發的人來說。 下麵這幾行代碼應該很熟悉了。 廢話不多說。直接看 app.UseAuthentication()的源碼 現在來看看var defau ...
前言:本文將會結合asp.net core 認證源碼來分析起認證的原理與流程。asp.net core版本2.2
對於大部分使用asp.net core開發的人來說。
下麵這幾行代碼應該很熟悉了。
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.Audience = "sp_api"; options.Authority = "http://localhost:5001"; options.SaveToken = true; })
app.UseAuthentication();
廢話不多說。直接看 app.UseAuthentication()的源碼
public class AuthenticationMiddleware { private readonly RequestDelegate _next; public AuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemes) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (schemes == null) { throw new ArgumentNullException(nameof(schemes)); } _next = next; Schemes = schemes; } public IAuthenticationSchemeProvider Schemes { get; set; } public async Task Invoke(HttpContext context) { context.Features.Set<IAuthenticationFeature>(new AuthenticationFeature { OriginalPath = context.Request.Path, OriginalPathBase = context.Request.PathBase }); // Give any IAuthenticationRequestHandler schemes a chance to handle the request var handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>(); foreach (var scheme in await Schemes.GetRequestHandlerSchemesAsync()) { var handler = await handlers.GetHandlerAsync(context, scheme.Name) as IAuthenticationRequestHandler; if (handler != null && await handler.HandleRequestAsync()) { return; } } var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); if (defaultAuthenticate != null) { var result = await context.AuthenticateAsync(defaultAuthenticate.Name); if (result?.Principal != null) { context.User = result.Principal; } } await _next(context); }
現在來看看var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync(); 幹了什麼。
在這之前。我們更應該要知道上面代碼中 public IAuthenticationSchemeProvider Schemes { get; set; } ,假如腦海中對這個IAuthenticationSchemeProvider類型的來源,有個清晰認識,對後面的理解會有很大的幫助
現在來揭秘IAuthenticationSchemeProvider 是從哪裡來添加到ioc的。
public static AuthenticationBuilder AddAuthentication(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddAuthenticationCore(); services.AddDataProtection(); services.AddWebEncoders(); services.TryAddSingleton<ISystemClock, SystemClock>(); return new AuthenticationBuilder(services); }
紅色代碼內部邏輯中就把IAuthenticationSchemeProvider添加到了IOC中。先來看看services.AddAuthenticationCore()的源碼,這個源碼的所在的解決方案的倉庫地址是https://github.com/aspnet/HttpAbstractions,這個倉庫目前已不再維護,其代碼都轉移到了asp.net core 倉庫 。
下麵為services.AddAuthenticationCore()的源碼
public static class AuthenticationCoreServiceCollectionExtensions { /// <summary> /// Add core authentication services needed for <see cref="IAuthenticationService"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <returns>The service collection.</returns> public static IServiceCollection AddAuthenticationCore(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.TryAddScoped<IAuthenticationService, AuthenticationService>(); services.TryAddSingleton<IClaimsTransformation, NoopClaimsTransformation>(); // Can be replaced with scoped ones that use DbContext services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>(); services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>(); return services; } /// <summary> /// Add core authentication services needed for <see cref="IAuthenticationService"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="configureOptions">Used to configure the <see cref="AuthenticationOptions"/>.</param> /// <returns>The service collection.</returns> public static IServiceCollection AddAuthenticationCore(this IServiceCollection services, Action<AuthenticationOptions> configureOptions) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configureOptions == null) { throw new ArgumentNullException(nameof(configureOptions)); } services.AddAuthenticationCore(); services.Configure(configureOptions); return services; } }
完全就可以看待添加了一個全局單例的IAuthenticationSchemeProvider對象。現在讓我們回到MiddleWare中探究Schemes.GetDefaultAuthenticateSchemeAsync(); 幹了什麼。光看方法的名字都能猜出就是獲取的預設的認證策略。
進入到IAuthenticationSchemeProvider 實現的源碼中,按我的經驗,來看先不急看GetDefaultAuthenticateSchemeAsync()裡面的內部邏輯。必須的看下IAuthenticationSchemeProvider實現類的構造函數。它的實現類是AuthenticationSchemeProvider。
先看看AuthenticationSchemeProvider的構造方法
public class AuthenticationSchemeProvider : IAuthenticationSchemeProvider { /// <summary> /// Creates an instance of <see cref="AuthenticationSchemeProvider"/> /// using the specified <paramref name="options"/>, /// </summary> /// <param name="options">The <see cref="AuthenticationOptions"/> options.</param> public AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options) : this(options, new Dictionary<string, AuthenticationScheme>(StringComparer.Ordinal)) { } /// <summary> /// Creates an instance of <see cref="AuthenticationSchemeProvider"/> /// using the specified <paramref name="options"/> and <paramref name="schemes"/>. /// </summary> /// <param name="options">The <see cref="AuthenticationOptions"/> options.</param> /// <param name="schemes">The dictionary used to store authentication schemes.</param> protected AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options, IDictionary<string, AuthenticationScheme> schemes) { _options = options.Value; _schemes = schemes ?? throw new ArgumentNullException(nameof(schemes)); _requestHandlers = new List<AuthenticationScheme>(); foreach (var builder in _options.Schemes) { var scheme = builder.Build(); AddScheme(scheme); } } private readonly AuthenticationOptions _options; private readonly object _lock = new object(); private readonly IDictionary<string, AuthenticationScheme> _schemes; private readonly List<AuthenticationScheme> _requestHandlers;
不難看出,上面的構造方法需要一個IOptions<AuthenticationOptions> 類型。沒有這個類型,而這個類型是從哪裡的了?
答:不知到各位是否記得addJwtBearer這個方法,再找個方法裡面就註入了AuthenticationOptions找個類型。
看源碼把
public static class JwtBearerExtensions { public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder) => builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, _ => { }); public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, Action<JwtBearerOptions> configureOptions) => builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions); public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, Action<JwtBearerOptions> configureOptions) => builder.AddJwtBearer(authenticationScheme, displayName: null, configureOptions: configureOptions); public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<JwtBearerOptions> configureOptions) { builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>()); return builder.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, displayName, configureOptions); } }
不難通過上述代碼看出它是及一個基於AuthenticationBuilder的擴展方法,而註入AuthenticationOptions的關鍵就在於 builder.AddScheme<JwtBearerOptions, JwtBearerHandler>(authenticationScheme, displayName, configureOptions); 這行代碼,按下F12看下源碼
public virtual AuthenticationBuilder AddScheme<TOptions, THandler>(string authenticationScheme, string displayName, Action<TOptions> configureOptions) where TOptions : AuthenticationSchemeOptions, new() where THandler : AuthenticationHandler<TOptions> => AddSchemeHelper<TOptions, THandler>(authenticationScheme, displayName, configureOptions); private AuthenticationBuilder AddSchemeHelper<TOptions, THandler>(string authenticationScheme, string displayName, Action<TOptions> configureOptions) where TOptions : class, new() where THandler : class, IAuthenticationHandler { Services.Configure<AuthenticationOptions>(o => { o.AddScheme(authenticationScheme, scheme => { scheme.HandlerType = typeof(THandler); scheme.DisplayName = displayName; }); }); if (configureOptions != null) { Services.Configure(authenticationScheme, configureOptions); } Services.AddTransient<THandler>(); return this; }
照舊還是分為2個方法來進行調用,其重點就是AddSchemeHelper找個方法。其裡面配置AuthenticationOptions類型。現在我們已經知道了IAuthenticationSchemeProvider何使註入的。還由AuthenticationSchemeProvider構造方法中IOptions<AuthenticationOptions> options是何使配置的,這樣我們就對於認證有了一個初步的認識。現在可以知道對於認證中間件,必須要有一個IAuthenticationSchemeProvider 類型。而這個IAuthenticationSchemeProvider的實現類的構造函數必須要由IOptions<AuthenticationOptions> options,沒有這兩個類型,認證中間件應該是不會工作的。
回到認證中間件中。繼續看var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();這句代碼,源碼如下
public virtual Task<AuthenticationScheme> GetDefaultAuthenticateSchemeAsync() => _options.DefaultAuthenticateScheme != null ? GetSchemeAsync(_options.DefaultAuthenticateScheme) : GetDefaultSchemeAsync(); public virtual Task<AuthenticationScheme> GetSchemeAsync(string name) => Task.FromResult(_schemes.ContainsKey(name) ? _schemes[name] : null); private Task<AuthenticationScheme> GetDefaultSchemeAsync() => _options.DefaultScheme != null ? GetSchemeAsync(_options.DefaultScheme)
: Task.FromResult<AuthenticationScheme>(null);
讓我們先驗證下方法1的三元表達式,應該執行那邊呢?通過前面的代碼我們知道AuthenticationOptions是在AuthenticationBuilder類型的AddSchemeHelper方法裡面進行配置的。經過我的調試,發現方法1會走右邊。其實最終還是從一個字典中取到了預設的AuthenticationScheme對象。到這裡中間件的裡面var defaultAuthenticate = await Schemes.GetDefaultAuthenticateSchemeAsync();代碼就完了。最終就那到了AuthenticationScheme的對象。
下麵來看看 中間件中var result = await context.AuthenticateAsync(defaultAuthenticate.Name);這句代碼幹了什麼。按下F12發現是一個擴展方法,還是到HttpAbstractions解決方案裡面找下源碼
源碼如下
public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string scheme) => context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme);
通過上面的方法,發現是通過IAuthenticationService的AuthenticateAsync() 來進行認證的。那麼現在IAuthenticationService這個類是乾什麼 呢?
下麵為IAuthenticationService的定義
public interface IAuthenticationService { Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme); Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties); Task ForbidAsync(HttpContext context, string scheme, AuthenticationProperties properties); Task SignInAsync(HttpContext context, string scheme, ClaimsPrincipal principal, AuthenticationProperties properties); Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties); }
IAuthenticationService的AuthenticateAsync()方法的實現源碼
public class AuthenticationService : IAuthenticationService { /// <summary> /// Constructor. /// </summary> /// <param name="schemes">The <see cref="IAuthenticationSchemeProvider"/>.</param> /// <param name="handlers">The <see cref="IAuthenticationRequestHandler"/>.</param> /// <param name="transform">The <see cref="IClaimsTransformation"/>.</param> public AuthenticationService(IAuthenticationSchemeProvider schemes, IAuthenticationHandlerProvider handlers, IClaimsTransformation transform) { Schemes = schemes; Handlers = handlers; Transform = transform; }public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme)
{
if (scheme == null)
{
var defaultScheme = await Schemes.GetDefaultAuthenticateSchemeAsync();
scheme = defaultScheme?.Name;
if (scheme == null)
{
throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found.");
}
} var handler = await Handlers.GetHandlerAsync(context, scheme);
if (handler == null)
{
throw await CreateMissingHandlerException(scheme);
} var result = await handler.AuthenticateAsync();
if (result != null && result.Succeeded)
{
var transformed = await Transform.TransformAsync(result.Principal);
return AuthenticateResult.Success(new AuthenticationTicket(transformed, result.Properties, result.Ticket.AuthenticationScheme));
}
return result;
}
通過構造方法可以看到這個類的構造方法需要IAuthenticationSchemeProvider類型和IAuthenticationHandlerProvider 類型,前面已經瞭解了IAuthenticationSchemeProvider是乾什麼的,取到配置的授權策略的名稱,那現在IAuthenticationHandlerProvider 是乾什麼的,看名字感覺應該是取到具體授權策略的handler.廢話補多少,看IAuthenticationHandlerProvider 介面定義把
public interface IAuthenticationHandlerProvider { /// <summary> /// Returns the handler instance that will be used. /// </summary> /// <param name="context">The context.</param> /// <param name="authenticationScheme">The name of the authentication scheme being handled.</param> /// <returns>The handler instance.</returns> Task<IAuthenticationHandler> GetHandlerAsync(HttpContext context, string authenticationScheme); }
通過上面的源碼,跟我猜想的不錯,果然就是取得具體的授權策略
現在我就可以知道AuthenticationService是對IAuthenticationSchemeProvider和IAuthenticationHandlerProvider封裝。最終調用IAuthentionHandel的AuthenticateAsync()方法進行認證。最終返回一個AuthenticateResult對象。
總結,對於asp.net core的認證來水,他需要下麵這幾個對象
AuthenticationBuilder 扶著對認證策略的配置與初始話
IAuthenticationHandlerProvider AuthenticationHandlerProvider 負責獲取配置了的認證策略的名稱
IAuthenticationSchemeProvider AuthenticationSchemeProvider 負責獲取具體認證策略的handle
IAuthenticationService AuthenticationService 實對上面兩個Provider 的封裝,來提供一個具體處理認證的入口
IAuthenticationHandler 和的實現類,是以哦那個來處理具體的認證的,對不同認證策略的出來,全是依靠的它的AuthenticateAsync()方法。
AuthenticateResult 最終的認證結果。
哎寫的太垃圾了。