簡體   English   中英

如何在ASP.NET核心中間件中強制執行實際的身份驗證工作流

[英]How to force actual authentication workflow in ASP.NET core middle ware

我想將一些基於身份驗證的用戶的應用程序上下文注入執行上下文中,以便業務/服務層可以透明地使用它。 我打算使用中間件進行設置。 啟動示例代碼為

app.UseAuthentication();

// my custom middleware
app.Use(async (context, next) =>
{
    // use context.User to build the application context 
    // ...

    // inject into execution context
    // ...
}

app.UseMvc(..)

不幸的是,在我的自定義中間件中,HttpContext.User.Identity.IsAuthenticated仍然為false。 命中MVC授權過濾器時,將觸發基於JWT令牌的實際身份驗證。 那么我該如何克服這個問題呢? 有沒有辦法知道實際的身份驗證階段何時完成(類似於經典ASP.NET管道中的global.asax),或者如何在中間件中強制實施身份驗證處理程序。 我嘗試使用擴展方法context.AuthenticateAsync強制構建實際的用戶主體,但徒勞無功。

我遇到的另一個問題是應用程序上下文的載體。 我之前選擇了AsycLocal<T>但是發現我在中間件中設置的內容在下游代碼中不可用。 因此,當前,我正在使用HttpContext.Items承載可以正常運行的應用程序上下文,但我AsycLocal<T>知道為什么AsycLocal<T>失敗。 是否不保證可以在ASP.NET管道的執行上下文中攜帶?

根據要求,ConfigureServices部分

    // Add Azure AD JWT Bearer Token support for API authentication
    services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
                       .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    ...
    // Add Azure AD OpenID authentication support for interactive UI
    services.AddAzureAdV2Authentication(Configuration);

還發現需要在策略中添加方案以使多個方案起作用

        // Add MVC with authentication/authorization
        services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .AddAuthenticationSchemes(AzureADDefaults.OpenIdScheme,
                    AzureADDefaults.JwtBearerAuthenticationScheme)
                .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })

最后,在我的中間件中,我嘗試使用如下代碼段強制執行身份驗證:

     if (!context.User.Identity.IsAuthenticated)
     {
          if(context.Request.Headers.ContainsKey(HeaderNames.Authorization))
          {
               await context.AuthenticateAsync(
                   AzureADDefaults.JwtBearerAuthenticationScheme);
          }
          else
          {
              // issue OpenID challange
              ...
          }
       }

      // here, I still found context.User.Identity.IsAuthenticated false

app.UseAuthentication()僅嘗試使用默認方案進行身份驗證,我猜測JWT令牌不是您的默認方案。 您可以嘗試使用context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme)來通過jwt方案進行身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM