對於大部分使用asp.net core開發的人來講。git
下面這幾行代碼應該很熟悉了。github
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()的源碼api
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(); 幹了什麼。
app
在這以前。咱們更應該要知道上面代碼中 public IAuthenticationSchemeProvider Schemes { get; set; } ,假如腦海中對這個IAuthenticationSchemeProvider類型的來源,有個清晰認識,對後面的理解會有很大的幫助
asp.net
如今來揭祕IAuthenticationSchemeProvider 是從哪裏來添加到ioc的。async
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 倉庫 。ide
下面爲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(); 幹了什麼。光看方法的名字都能猜出就是獲取的默認的認證策略。oop
進入到IAuthenticationSchemeProvider 實現的源碼中,按個人經驗,來看先不急看GetDefaultAuthenticateSchemeAsync()裏面的內部邏輯。必須的看下IAuthenticationSchemeProvider實現類的構造函數。它的實現類是AuthenticationSchemeProvider。ui
先看看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; }
經過構造方法能夠看到這個類的構造方法須要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對象。
AuthenticationBuilder 扶着對認證策略的配置與初始話
IAuthenticationHandlerProvider AuthenticationHandlerProvider 負責獲取配置了的認證策略的名稱
IAuthenticationSchemeProvider AuthenticationSchemeProvider 負責獲取具體認證策略的handle
IAuthenticationService AuthenticationService 實對上面兩個Provider 的封裝,來提供一個具體處理認證的入口
IAuthenticationHandler 和的實現類,是以哦那個來處理具體的認證的,對不一樣認證策略的出來,全是依靠的它的AuthenticateAsync()方法。
AuthenticateResult 最終的認證結果。
哎寫的太垃圾了。