在创建Handler的时候,是先从AuthenticationScheme中获取,如果不存在则通过ActivatorUtilities创建。 获取到Handle后,将会放在_handlerMap字典里面,当下次获取Handler的时候,将直接从缓存中获取。
IAuthenticationService
这个对象是在AuthenticationMiddleware中最后才用到的,而且是基于HttpContext的扩展被调用
public static class AuthenticationHttpContextExtensions { public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string scheme) => context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme); .... }
这里主要调用了IAuthenticationService的AuthenticateAsync方法,看一下这个方法做了什么
public class AuthenticationService : IAuthenticationService { public IAuthenticationSchemeProvider Schemes { get; } public IAuthenticationHandlerProvider Handlers { get; } public IClaimsTransformation Transform { get; } public virtual async Task<AuthenticateResult> AuthenticateAsync(HttpContext context, string scheme) { if (scheme == null) { var scheme = (await this.Schemes.GetDefaultAuthenticateSchemeAsync())?.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 this.CreateMissingHandlerException(scheme); AuthenticateResult result = await handler.AuthenticateAsync(); if (result != null && result.Succeeded) return AuthenticateResult.Success(new AuthenticationTicket(await Transform.TransformAsync(result.Principal), result.Properties, result.Ticket.AuthenticationScheme)); return result; } }
这里其实就是我们在前面讲的根据Scheme获取对应的AuthenticationHandler,然后调用AuthenticateAsync()方法,这个方法调用了核心方法HandleAuthenticateOnceAsync,然后再调用HandleAuthenticateAsync()这个核心的认证方法。
从上图看到这个HandleAuthenticateAsync是个抽象方法,我们的子类都需要实现这个方法的动作,基于本文的例子,我们看一下JwtBearerHandler的一个实际认证。
public class JwtBearerHandler : AuthenticationHandler<JwtBearerOptions> { protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { JwtBearerHandler jwtBearerHandler = this; string token = (string) null; object obj; AuthenticationFailedContext authenticationFailedContext; int num; try { MessageReceivedContext messageReceivedContext = new MessageReceivedContext(jwtBearerHandler.Context, jwtBearerHandler.Scheme, jwtBearerHandler.Options); await jwtBearerHandler.Events.MessageReceived(messageReceivedContext); if (messageReceivedContext.Result != null) return messageReceivedContext.Result; token = messageReceivedContext.Token; if (string.IsNullOrEmpty(token)) { string header = (string) jwtBearerHandler.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(header)) return AuthenticateResult.NoResult(); if (header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) token = header.Substring("Bearer ".Length).Trim(); if (string.IsNullOrEmpty(token)) return AuthenticateResult.NoResult(); } if (jwtBearerHandler._configuration == null && jwtBearerHandler.Options.ConfigurationManager != null) { OpenIdConnectConfiguration configurationAsync = await jwtBearerHandler.Options.ConfigurationManager.GetConfigurationAsync(jwtBearerHandler.Context.RequestAborted); jwtBearerHandler._configuration = configurationAsync; } TokenValidationParameters validationParameters1 = jwtBearerHandler.Options.TokenValidationParameters.Clone(); if (jwtBearerHandler._configuration != null) { string[] strArray = new string[1] { jwtBearerHandler._configuration.Issuer }; TokenValidationParameters validationParameters2 = validationParameters1; IEnumerable<string> validIssuers = validationParameters1.get_ValidIssuers(); object obj1 = (validIssuers != null ? (object) validIssuers.Concat<string>((IEnumerable<string>) strArray) : (object) null) ?? (object) strArray; validationParameters2.set_ValidIssuers((IEnumerable<string>) obj1); TokenValidationParameters validationParameters3 = validationParameters1; IEnumerable<SecurityKey> issuerSigningKeys = validationParameters1.get_IssuerSigningKeys(); IEnumerable<SecurityKey> securityKeys = (issuerSigningKeys != null ? issuerSigningKeys.Concat<SecurityKey>((IEnumerable<SecurityKey>) jwtBearerHandler._configuration.get_SigningKeys()) : (IEnumerable<SecurityKey>) null) ?? (IEnumerable<SecurityKey>) jwtBearerHandler._configuration.get_SigningKeys(); validationParameters3.set_IssuerSigningKeys(securityKeys); } List<Exception> exceptionList = (List<Exception>) null; foreach (ISecurityTokenValidator securityTokenValidator in (IEnumerable<ISecurityTokenValidator>) jwtBearerHandler.Options.SecurityTokenValidators) { if (securityTokenValidator.CanReadToken(token)) { SecurityToken securityToken; ClaimsPrincipal claimsPrincipal; try { claimsPrincipal = securityTokenValidator.ValidateToken(token, validationParameters1, ref securityToken); } catch (Exception ex) { jwtBearerHandler.Logger.TokenValidationFailed(ex); if (jwtBearerHandler.Options.RefreshOnIssuerKeyNotFound && jwtBearerHandler.Options.ConfigurationManager != null && ex is SecurityTokenSignatureKeyNotFoundException) jwtBearerHandler.Options.ConfigurationManager.RequestRefresh(); if (exceptionList == null) exceptionList = new List<Exception>(1); exceptionList.Add(ex); continue; } jwtBearerHandler.Logger.TokenValidationSucceeded(); TokenValidatedContext validatedContext = new TokenValidatedContext(jwtBearerHandler.Context, jwtBearerHandler.Scheme, jwtBearerHandler.Options); validatedContext.Principal = claimsPrincipal; validatedContext.SecurityToken = securityToken; TokenValidatedContext tokenValidatedContext = validatedContext; await jwtBearerHandler.Events.TokenValidated(tokenValidatedContext); if (tokenValidatedContext.Result != null) return tokenValidatedContext.Result; if (jwtBearerHandler.Options.SaveToken) tokenValidatedContext.Properties.StoreTokens((IEnumerable<AuthenticationToken>) new AuthenticationToken[1] { new AuthenticationToken() { Name = "access_token", Value = token } }); tokenValidatedContext.Success(); return tokenValidatedContext.Result; } } if (exceptionList == null) return AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"); authenticationFailedContext = new AuthenticationFailedContext(jwtBearerHandler.Context, jwtBearerHandler.Scheme, jwtBearerHandler.Options) { Exception = exceptionList.Count == 1 ? exceptionList[0] : (Exception) new AggregateException((IEnumerable<Exception>) exceptionList) }; await jwtBearerHandler.Events.AuthenticationFailed(authenticationFailedContext); return authenticationFailedContext.Result == null ? AuthenticateResult.Fail(authenticationFailedContext.Exception) : authenticationFailedContext.Result; } catch (Exception ex) { obj = (object) ex; num = 1; } if (num == 1) { Exception ex = (Exception) obj; jwtBearerHandler.Logger.ErrorProcessingMessage(ex); authenticationFailedContext = new AuthenticationFailedContext(jwtBearerHandler.Context, jwtBearerHandler.Scheme, jwtBearerHandler.Options) { Exception = ex }; await jwtBearerHandler.Events.AuthenticationFailed(authenticationFailedContext); if (authenticationFailedContext.Result != null) return authenticationFailedContext.Result; Exception source = obj as Exception; if (source == null) throw obj; ExceptionDispatchInfo.Capture(source).Throw(); authenticationFailedContext = (AuthenticationFailedContext) null; } obj = (object) null; token = (string) null; AuthenticateResult authenticateResult; return authenticateResult; } }