久久99久久人婷婷精品综合_超碰aⅴ人人做人人爽欧美_亚洲电影第三页_日韩欧美一中文字暮专区_波多野结衣的一区二区三区_婷婷在线播放_人人视频精品_国产精品日韩精品欧美精品_亚洲免费黄色_欧美性猛交xxxxxxxx

ASP.NETCoreAuthentication如何認(rèn)證實(shí)現(xiàn)方法-創(chuàng)新互聯(lián)

小編給大家分享一下ASP.NET Core Authentication如何認(rèn)證實(shí)現(xiàn)方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)提供成都網(wǎng)站制作、網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì),成都品牌網(wǎng)站建設(shè),廣告投放等致力于企業(yè)網(wǎng)站建設(shè)與公司網(wǎng)站制作,十年的網(wǎng)站開發(fā)和建站經(jīng)驗(yàn),助力企業(yè)信息化建設(shè),成功案例突破數(shù)千家,是您實(shí)現(xiàn)網(wǎng)站建設(shè)的好選擇.

追本溯源,從使用開始  

首先看一下我們通常是如何使用微軟自帶的認(rèn)證,一般在Startup里面配置我們所需的依賴認(rèn)證服務(wù),這里通過JWT的認(rèn)證方式講解

public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthentication(authOpt =>
  {
    authOpt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    authOpt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  })
  .AddJwtBearer(o =>
  {
    o.TokenValidationParameters = new TokenValidationParameters
    {
      //配置自己所要驗(yàn)證的參數(shù)
      
    };
  });
}

我們來看一下源碼AddAuthentication主要做了什么

public static class AuthenticationServiceCollectionExtensions
 {
  public static AuthenticationBuilder AddAuthentication( this IServiceCollection services, Action<AuthenticationOptions> configureOptions)
  {
   if (services == null)
    throw new ArgumentNullException(nameof (services));
   if (configureOptions == null)
    throw new ArgumentNullException(nameof (configureOptions));
   AuthenticationBuilder authenticationBuilder = services.AddAuthentication();
   services.Configure<AuthenticationOptions>(configureOptions);
   return authenticationBuilder;
  }

  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);
  }

  public static AuthenticationBuilder AddAuthentication(
   this IServiceCollection services,
   string defaultScheme)
  {
   return services.AddAuthentication((Action<AuthenticationOptions>) (o => o.DefaultScheme = defaultScheme));
  } 

 .....
}

ConfigureServices方法基本都是服務(wù)的注冊,基于微軟的風(fēng)格,這里的AddAuthenticationCore肯定是我們的認(rèn)證服務(wù)注冊方法,來看一下

public static class AuthenticationCoreServiceCollectionExtensions
 {
  /// <summary>
  /// Add core authentication services needed for <see cref="T:Microsoft.AspNetCore.Authentication.IAuthenticationService" />.
  /// </summary>  
  public static IServiceCollection AddAuthenticationCore(
   this IServiceCollection services)
  {
   if (services == null)
    throw new ArgumentNullException(nameof (services));
   services.TryAddScoped<IAuthenticationService, AuthenticationService>();
   services.TryAddSingleton<IClaimsTransformation, NoopClaimsTransformation>();
   services.TryAddScoped<IAuthenticationHandlerProvider, AuthenticationHandlerProvider>();
   services.TryAddSingleton<IAuthenticationSchemeProvider, AuthenticationSchemeProvider>();
   return services;
  }

  /// <summary>
  /// Add core authentication services needed for <see cref="T:Microsoft.AspNetCore.Authentication.IAuthenticationService" />.
  /// </summary>  
  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<AuthenticationOptions>(configureOptions);
   return services;
  }
 }

我們看到這里主要注冊了AuthenticationService, AuthenticationHandlerProvider, AuthenticationSchemeProvider這三個(gè)對(duì)象,如文章開頭所說,追本溯源,從使用開始,我們先看一下這三個(gè)對(duì)象是如何在認(rèn)證體系中使用的,且是如何發(fā)揮作用的。

從使用開始

看一下我們的認(rèn)證管道構(gòu)建

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  {
    ...
    app.UseAuthentication();
    ...
  }


 public static class AuthAppBuilderExtensions
 {
  public static IApplicationBuilder UseAuthentication( this IApplicationBuilder app)
  {
   if (app == null)
    throw new ArgumentNullException(nameof (app));
   return app.UseMiddleware<AuthenticationMiddleware>();
  }
 }

這里使用了約定的注冊方式UseMiddleware,并且指定使用中間件AuthenticationMiddleware  

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));
   this._next = next;
   this.Schemes = schemes;
  }

  public IAuthenticationSchemeProvider Schemes { get; set; }

  public async Task Invoke(HttpContext context)
  {
   context.Features.Set<IAuthenticationFeature>((IAuthenticationFeature) new AuthenticationFeature()
   {
    OriginalPath = context.Request.Path,
    OriginalPathBase = context.Request.PathBase
   });
   IAuthenticationHandlerProvider handlers = context.RequestServices.GetRequiredService<IAuthenticationHandlerProvider>();
   foreach (AuthenticationScheme authenticationScheme in await this.Schemes.GetRequestHandlerSchemesAsync())
   {
    IAuthenticationRequestHandler handlerAsync = await handlers.GetHandlerAsync(context, authenticationScheme.Name) as IAuthenticationRequestHandler;
    bool flag = handlerAsync != null;
    if (flag)
     flag = await handlerAsync.HandleRequestAsync();
    if (flag)
     return;
   }
   AuthenticationScheme authenticateSchemeAsync = await this.Schemes.GetDefaultAuthenticateSchemeAsync();
   if (authenticateSchemeAsync != null)
   {
    AuthenticateResult authenticateResult = await context.AuthenticateAsync(authenticateSchemeAsync.Name);  //實(shí)際的認(rèn)證業(yè)務(wù)
    if (authenticateResult?.Principal != null)
     context.User = authenticateResult.Principal;
   }
   await this._next(context);
  }
 }

在繼續(xù)往下之前,我們先看一下這個(gè)認(rèn)證中間件的作用結(jié)果,當(dāng)認(rèn)證通過時(shí),在HttpContext的User屬性(ClaimPrincipal)賦予身份標(biāo)識(shí),所以在后續(xù)的請求管道中都是基于認(rèn)證結(jié)果中的身份標(biāo)識(shí)做鑒權(quán),這個(gè)我們會(huì)在后面的實(shí)際操作中會(huì)提到。

言歸正傳,在這里引出了我們的兩個(gè)對(duì)象AuthenticationHandlerProvider,AuthenticationSchemeProvider。

重要對(duì)象講解

IAuthenticationSchemeProvider

從名字來看,IAuthenticationSchemeProvider的作用應(yīng)該是提供Scheme的,這也是Provider在微軟的風(fēng)格里面起的作用(類似于工廠模式)。

這個(gè)Scheme是什么呢?很明顯,在Framework時(shí)代,也是有基于不同Scheme驗(yàn)證的,比如Bearer,Cookie,在Aspnet Core中定義不同的Scheme代表著不同的認(rèn)證處理方式,具體體現(xiàn)是在每個(gè)Scheme中包含對(duì)應(yīng)的IAuthenticationHandler類型的Handler,由它來完成跟自身Scheme相關(guān)的認(rèn)證處理。如果沒有定義會(huì)怎么樣?仔細(xì)看上面這塊源碼,只有當(dāng)AuthenticationScheme不為空時(shí)才會(huì)做認(rèn)證,否則一旦在Controller打上鑒權(quán)標(biāo)簽[Authorize],將會(huì)直接返回401,所以我們必須指定自己的Scheme。

那么我們在哪里指定我們的Scheme類似呢?我們先返回到ConfigureService的AddJwtBearer,使用過的朋友們肯定知道,這里獲取的Scheme是我們在ConfigureService通過Addxxx scheme指定的Scheme類型。這里我們是使用JWT的

ASP.NET Core Authentication如何認(rèn)證實(shí)現(xiàn)方法

在這里指定了TOptions 為JwtBearerOptions,而THandler為JwtBearerHandler。

public virtual AuthenticationBuilder AddScheme<TOptions, THandler>(
   string authenticationScheme,
   string displayName,
   Action<TOptions> configureOptions)
   where TOptions : AuthenticationSchemeOptions, new()
   where THandler : AuthenticationHandler<TOptions>
  {
   return this.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
  {
   this.Services.Configure<AuthenticationOptions>((Action<AuthenticationOptions>) (o => o.AddScheme(authenticationScheme, (Action<AuthenticationSchemeBuilder>) (scheme =>
   {
    scheme.HandlerType = typeof (THandler);
    scheme.DisplayName = displayName;
   }))));
   if (configureOptions != null)
    this.Services.Configure<TOptions>(authenticationScheme, configureOptions);
   this.Services.AddTransient<THandler>();
   return this;
  }

注意這里TOptions 是需要繼承AuthenticationSchemeOptions的,在這里是JwtBearerOptions,而THandler是AuthenticationHandler<TOptions>類型的Handler,在這里是JwtBearerHandler。

ASP.NET Core Authentication如何認(rèn)證實(shí)現(xiàn)方法

我們回到Scheme的分析繼續(xù)往下,首先看一下AuthenticationScheme的定義  

public class AuthenticationScheme
 {
  /// <summary>Constructor.</summary>  
  public AuthenticationScheme(string name, string displayName, Type handlerType)
  {
   if (name == null)
    throw new ArgumentNullException(nameof (name));
   if (handlerType == (Type) null)
    throw new ArgumentNullException(nameof (handlerType));
   if (!typeof (IAuthenticationHandler).IsAssignableFrom(handlerType))
    throw new ArgumentException("handlerType must implement IAuthenticationHandler.");
   this.Name = name;
   this.HandlerType = handlerType;
   this.DisplayName = displayName;
  }

  /// <summary>The name of the authentication scheme.</summary>
  public string Name { get; }

  /// <summary>
  /// The display name for the scheme. Null is valid and used for non user facing schemes.
  /// </summary>
  public string DisplayName { get; }

  /// <summary>
  /// The <see cref="T:Microsoft.AspNetCore.Authentication.IAuthenticationHandler" /> type that handles this scheme.
  /// </summary>
  public Type HandlerType { get; }
 }

在這里可以看到,如果要使用Aspnet Core自身的認(rèn)證體系,需先注冊Scheme,并且該Scheme必須指定一個(gè)類型為IAuthenticationHandler的Handler,否則會(huì)拋出異常。(這個(gè)其實(shí)在AddxxxScheme的時(shí)候已經(jīng)指定了AuthenticationHandler)

我們再看一下IAuthenticationSchemeProvider的GetRequestHandlerSchemesAsync方法做了什么

public virtual Task<IEnumerable<AuthenticationScheme>> GetRequestHandlerSchemesAsync()
  {
   return Task.FromResult<IEnumerable<AuthenticationScheme>>((IEnumerable<AuthenticationScheme>) this._requestHandlers);
  }

這東西返回了_requestHandlers,這是什么?看代碼

public class AuthenticationSchemeProvider : IAuthenticationSchemeProvider
 {
  private readonly object _lock = new object();
  private readonly AuthenticationOptions _options;
  private readonly IDictionary<string, AuthenticationScheme> _schemes;
  private readonly List<AuthenticationScheme> _requestHandlers;

  /// <summary>
  /// Creates an instance of <see cref="T:Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider" />
  /// using the specified <paramref name="options" />,
  /// </summary>  
  public AuthenticationSchemeProvider(IOptions<AuthenticationOptions> options)
   : this(options, (IDictionary<string, AuthenticationScheme>) new Dictionary<string, AuthenticationScheme>((IEqualityComparer<string>) StringComparer.Ordinal))
  {
  }

  /// <summary>
  /// Creates an instance of <see cref="T:Microsoft.AspNetCore.Authentication.AuthenticationSchemeProvider" />
  /// using the specified <paramref name="options" /> and <paramref name="schemes" />.
  /// </summary>  
  protected AuthenticationSchemeProvider(
   IOptions<AuthenticationOptions> options,
   IDictionary<string, AuthenticationScheme> schemes)
  {
   this._options = options.Value;
   IDictionary<string, AuthenticationScheme> dictionary = schemes;
   if (dictionary == null)
    throw new ArgumentNullException(nameof (schemes));
   this._schemes = dictionary;
   this._requestHandlers = new List<AuthenticationScheme>();
   foreach (AuthenticationSchemeBuilder scheme in this._options.Schemes)
    this.AddScheme(scheme.Build());
  }

  public virtual void AddScheme(AuthenticationScheme scheme)
  {
   if (this._schemes.ContainsKey(scheme.Name))
    throw new InvalidOperationException("Scheme already exists: " + scheme.Name);
   lock (this._lock)
   {
    if (this._schemes.ContainsKey(scheme.Name))
     throw new InvalidOperationException("Scheme already exists: " + scheme.Name);
    if (typeof (IAuthenticationRequestHandler).IsAssignableFrom(scheme.HandlerType))
     this._requestHandlers.Add(scheme);
    this._schemes[scheme.Name] = scheme;
   }
  }
.....
}

這東西就是把我們在認(rèn)證注冊服務(wù)中指定的scheme,通過解析出的AuthenticationSchemeProvider 的構(gòu)造函數(shù)加載來的,進(jìn)而返回一系列的List<AuthenticationScheme>,OK拿到這些scheme之后有什么用呢?這里引出了我們的第二個(gè)對(duì)象AuthenticationHandlerProvider,下面我們來了解一下?! ?/p>

IAuthenticationHandlerProvider

我們看到,AuthenticationMiddleware中用到了IAuthenticationHandlerProvider的GetHandlerAsync方法,那我們先看一下這個(gè)方法的作用

public class AuthenticationHandlerProvider : IAuthenticationHandlerProvider
 {
  private Dictionary<string, IAuthenticationHandler> _handlerMap = new Dictionary<string, IAuthenticationHandler>((IEqualityComparer<string>) StringComparer.Ordinal);

  /// <summary>Constructor.</summary>
  public AuthenticationHandlerProvider(IAuthenticationSchemeProvider schemes)
  {
   this.Schemes = schemes;
  }

  /// <summary>
  /// The <see cref="T:Microsoft.AspNetCore.Authentication.IAuthenticationHandlerProvider" />.
  /// </summary>
  public IAuthenticationSchemeProvider Schemes { get; }

  /// <summary>Returns the handler instance that will be used.</summary>  
  public async Task<IAuthenticationHandler> GetHandlerAsync( HttpContext context, string authenticationScheme)
  {
   if (this._handlerMap.ContainsKey(authenticationScheme))
    return this._handlerMap[authenticationScheme];
   AuthenticationScheme schemeAsync = await this.Schemes.GetSchemeAsync(authenticationScheme);
   if (schemeAsync == null)
    return (IAuthenticationHandler) null;
   IAuthenticationHandler handler = (context.RequestServices.GetService(schemeAsync.HandlerType) ?? ActivatorUtilities.CreateInstance(context.RequestServices, schemeAsync.HandlerType)) as IAuthenticationHandler;
   if (handler != null)
   {
    await handler.InitializeAsync(schemeAsync, context);
    this._handlerMap[authenticationScheme] = handler;
   }
   return handler;
  }
 }

在創(chuàng)建Handler的時(shí)候,是先從AuthenticationScheme中獲取,如果不存在則通過ActivatorUtilities創(chuàng)建。 獲取到Handle后,將會(huì)放在_handlerMap字典里面,當(dāng)下次獲取Handler的時(shí)候,將直接從緩存中獲取。

IAuthenticationService

這個(gè)對(duì)象是在AuthenticationMiddleware中最后才用到的,而且是基于HttpContext的擴(kuò)展被調(diào)用

public static class AuthenticationHttpContextExtensions
{
  public static Task<AuthenticateResult> AuthenticateAsync(this HttpContext context, string scheme) =>
    context.RequestServices.GetRequiredService<IAuthenticationService>().AuthenticateAsync(context, scheme);

 ....     
}

這里主要調(diào)用了IAuthenticationService的AuthenticateAsync方法,看一下這個(gè)方法做了什么

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;
  }
}

這里其實(shí)就是我們在前面講的根據(jù)Scheme獲取對(duì)應(yīng)的AuthenticationHandler,然后調(diào)用AuthenticateAsync()方法,這個(gè)方法調(diào)用了核心方法HandleAuthenticateOnceAsync,然后再調(diào)用HandleAuthenticateAsync()這個(gè)核心的認(rèn)證方法。

ASP.NET Core Authentication如何認(rèn)證實(shí)現(xiàn)方法

從上圖看到這個(gè)HandleAuthenticateAsync是個(gè)抽象方法,我們的子類都需要實(shí)現(xiàn)這個(gè)方法的動(dòng)作,基于本文的例子,我們看一下JwtBearerHandler的一個(gè)實(shí)際認(rèn)證。  

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;
  }
}

這個(gè)方法有點(diǎn)長,主要是從Request.Headers里面獲取Authorization的Bearer出來解析,再在AddJwtBearer中傳入的委托參數(shù)JwtBearerOptions的TokenValidationParameters屬性作為依據(jù)進(jìn)行對(duì)比來進(jìn)行認(rèn)證是否通過與否。

總結(jié)

本文對(duì) ASP.NET Core 的認(rèn)證流程做了一個(gè)源碼分析流程介紹,由于是源碼分析篇,所以可能會(huì)比較枯燥和苦澀難懂。在后面的真正使用過程中,然后再結(jié)合本篇的一個(gè)總結(jié)流程,相信大家會(huì)逐漸開朗。

  • 在Startup類中的ConfigureServices方法通過添加AddAuthentication注冊我們最主要的三個(gè)對(duì)象AuthenticationService, AuthenticationHandlerProvider, AuthenticationSchemeProvider

  • 通過AddAuthentication返回的AuthenticationBuilder 通過AddJwtBearer(或者AddCookie)來指定Scheme類型和需要驗(yàn)證的參數(shù)

  • 在Startup類中的Configure方法通過添加UseAuthentication注冊認(rèn)證中間件

  • 在認(rèn)證過程中,通過AuthenticationSchemeProvider獲取正確的Scheme,在AuthenticationService中通過Scheme和AuthenticationHandlerProvider獲取正確的AuthenticationHandler,最后通過對(duì)應(yīng)的AuthenticationHandler的AuthenticateAsync方法進(jìn)行認(rèn)證流程

以上是“ASP.NET Core Authentication如何認(rèn)證實(shí)現(xiàn)方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!

名稱欄目:ASP.NETCoreAuthentication如何認(rèn)證實(shí)現(xiàn)方法-創(chuàng)新互聯(lián)
本文地址:http://www.js-pz168.com/article30/idoso.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動(dòng)態(tài)網(wǎng)站網(wǎng)站設(shè)計(jì)關(guān)鍵詞優(yōu)化ChatGPT企業(yè)網(wǎng)站制作網(wǎng)頁設(shè)計(jì)公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司
久久99久久人婷婷精品综合_超碰aⅴ人人做人人爽欧美_亚洲电影第三页_日韩欧美一中文字暮专区_波多野结衣的一区二区三区_婷婷在线播放_人人视频精品_国产精品日韩精品欧美精品_亚洲免费黄色_欧美性猛交xxxxxxxx
亚洲一区二区三区欧美| 欧美日韩在线播放| 9191久久久久久久久久久| 久久久久久久久久久久久夜| 亚洲精品网站在线观看| 国内一区二区视频| 国产一区二区三区黄| 91黄色免费版| 国产肉丝袜一区二区| 天天操天天色综合| 北条麻妃一区二区三区| 午夜老司机精品| 日韩精品影音先锋| 亚洲成人午夜电影| av一区二区三区在线| 亚洲一区二三| 国产亚洲欧美日韩俺去了| 日韩二区三区在线观看| 91美女福利视频| 一本久久a久久免费精品不卡| 久久久不卡网国产精品二区| 视频一区在线视频| 91在线在线观看| 欧美亚一区二区| 中文字幕日韩欧美一区二区三区| 精久久久久久久久久久| 精品人伦一区二区三区| 91精品国产全国免费观看| 亚洲精品va在线观看| 成人av动漫在线| 一区二区视频在线观看| 日本一区二区三区视频视频| 久久99精品久久久久久久久久久久| 国产在线精品一区二区中文| 在线不卡欧美精品一区二区三区| 一区二区三区精品| 99久久99久久综合| 欧美在线观看视频在线| 亚洲日本在线天堂| 成人夜色视频网站在线观看| 一级日韩一区在线观看| 国产三级欧美三级日产三级99| 美女视频一区二区三区| 免费99视频| 久久久国际精品| 国产一区二区女| 亚洲ai欧洲av| 国产精品亲子伦对白| 国产丶欧美丶日本不卡视频| 亚洲国产一区二区精品视频| 国产欧美一区二区在线观看| 国内外成人在线视频| 亚洲视频导航| 亚洲视频1区2区| 91亚洲国产成人精品一区二区三 | 一本久久a久久精品亚洲| 国产精品美女久久久久久2018| 国产福利91精品一区| 色婷婷av一区| 一区二区三区欧美日韩| 高清国产在线一区| 精品免费国产二区三区| 久久不见久久见免费视频7 | 亚洲免费电影在线| yellow视频在线观看一区二区| 欧美一区二区三区成人| 麻豆精品一二三| 一区二区三区四区视频在线| 亚洲精品国产无套在线观| 99视频国产精品免费观看| 日韩欧美色电影| 久久99深爱久久99精品| 亚洲在线欧美| 亚洲自拍欧美精品| 欧美成人dvd在线视频| 国产精品免费aⅴ片在线观看| 成人av在线资源| 日韩一区二区三区在线观看| 久久99国产精品麻豆| 色婷婷亚洲一区二区三区| 亚洲电影在线免费观看| 日本a级片久久久| 亚洲免费看黄网站| 国产一区二区三区无遮挡| 国产日产精品1区| 91亚洲国产成人精品一区二三 | 国产精品久久久久永久免费观看| 91网站在线播放| 2021久久国产精品不只是精品| 国产高清亚洲一区| 制服丝袜日韩国产| 国产美女精品人人做人人爽| 欧美亚洲国产一区二区三区va| 日韩av网站免费在线| 伊人色综合影院| 天堂va蜜桃一区二区三区 | 亚洲午夜三级在线| 日韩和欧美的一区二区| 一区二区三区在线观看网站| 欧美另类一区| 亚洲在线观看免费视频| 欧美一区激情视频在线观看| 一区二区成人在线视频| 热re99久久精品国99热蜜月| 一二三四区精品视频| 日韩精品无码一区二区三区| 一区二区免费在线播放| 日本一区免费在线观看| 一区二区三区高清不卡| 天堂资源在线亚洲资源| 午夜精品久久一牛影视| 色婷婷久久久综合中文字幕| 青青草视频一区| 欧美日韩国产一二三| 国产精品一二三四五| 日韩欧美国产精品| 不卡视频一二三四| 久久久噜噜噜久噜久久综合| 动漫美女被爆操久久久| 亚洲欧美在线高清| 日本不卡二区| 视频一区免费在线观看| 欧美日韩中文另类| 国产99久久久国产精品| 26uuu色噜噜精品一区二区| 不卡一区二区三区视频| 日韩一区日韩二区| 日韩精品一线二线三线| 日韩av一二三| 9191久久久久久久久久久| av网站免费线看精品| 国产精品网站一区| 欧美日韩在线播放一区二区| 午夜精品一区二区三区三上悠亚| 欧美在线观看视频一区二区三区| 国产精品白丝av| 国产日韩三级在线| 欧美精品一区二区三区四区五区 | 欧洲精品在线观看| 国产成人午夜99999| 久久久精品国产免大香伊| 久久精品人成| 日韩av中文字幕一区二区| 欧美麻豆精品久久久久久| 波多野结衣视频一区| 国产精品久久网站| 亚洲三区在线| 国产精品主播直播| 国产女人18水真多18精品一级做| 久久免费看av| 男人的天堂亚洲一区| 日韩视频在线一区二区| 国产精品视频在线免费观看| 亚洲国产精品一区二区久久 | 亚洲欧美日韩久久精品| 色偷偷久久一区二区三区| 顶级嫩模精品视频在线看| 国产精品污网站| 伊人久久av导航| 成人av网站在线| 亚洲久草在线视频| 欧美天堂亚洲电影院在线播放 | 精品国产乱码久久久久久牛牛| 国产精品久久精品国产| 午夜精品久久久久影视| 日韩欧美一区电影| 久久精彩视频| 久久国产精品72免费观看| 久久久久久久久99精品| 视频二区一区| 国产v综合v亚洲欧| 亚洲日本一区二区三区| 欧美日韩中文字幕一区二区| 99国产高清| 石原莉奈在线亚洲二区| 26uuu欧美| 亚洲国产精品一区在线观看不卡| 国产99久久久久| 尤物av一区二区| 91精品国产91久久久久久最新毛片| 国产一区国产精品| 久草在线在线精品观看| 国产精品欧美久久久久一区二区| 色婷婷久久综合| 俄罗斯精品一区二区| 美腿丝袜亚洲综合| 国产精品日日摸夜夜摸av| 在线免费观看不卡av| 国产精品三区在线| 国产在线国偷精品产拍免费yy| 国产精品久久久久久久久快鸭| 欧美午夜影院一区| 狠狠色综合色区| 国产精品亚洲а∨天堂免在线| 日韩理论电影院| 日韩亚洲欧美一区二区三区| 三区精品视频| 91网页版在线| 久久草av在线| 亚洲女人的天堂|