Asp.net

Identity Server 3 - Ajax 呼叫上的 401 而不是 302

  • June 15, 2020

我有一個 web api / mvc 混合應用程序,我已將其配置為使用 cookie 身份驗證。這適用於應用程序的 mvc 部分。Web api 確實強制執行授權,但它不是返回 a401 - Unauthorised而是返回 a302 - Found並重定向到登錄頁面。我寧願它返回一個401. 我試圖掛接到CookieAuthenticationProvider.OnApplyRedirect委託,但這似乎沒有被呼叫。我錯過了什麼?我目前的設置如下:

AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
   AuthenticationType = "Cookies",
   ExpireTimeSpan = TimeSpan.FromMinutes(20),
   SlidingExpiration = true,
   CookieHttpOnly = true,
   CookieSecure = CookieSecureOption.Never, //local non ssl-dev only
   Provider = new CookieAuthenticationProvider
   {
       OnApplyRedirect = ctx =>
       {
           if (!IsAjaxRequest(ctx.Request))
           {
               ctx.Response.Redirect(ctx.RedirectUri);
           }
       }
   }
});

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
   Authority = IdentityConfig.Authority,
   ClientId = IdentityConfig.SoftwareClientId,
   Scope = "openid profile roles",
   RedirectUri = IdentityConfig.RedirectUri,
   ResponseType = "id_token",
   SignInAsAuthenticationType = "Cookies"
});

在您的範例中,UseCookieAuthentication不再控制它,而是控制UseOpenIdConnectAuthentication它。這涉及使用Notifications屬性和攔截 OpenID Connect 身份驗證請求。

嘗試以下方法以獲得靈感:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
   Authority = IdentityConfig.Authority,
   ClientId = IdentityConfig.SoftwareClientId,
   Scope = "openid profile roles",
   RedirectUri = IdentityConfig.RedirectUri,
   ResponseType = "id_token",
   SignInAsAuthenticationType = "Cookies",
   Notifications = new OpenIdConnectAuthenticationNotifications
   {
       RedirectToIdentityProvider = notification =>
       {
           if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
           {
               if (IsAjaxRequest(notification.Request) && notification.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
               {
                   notification.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                   notification.HandleResponse();
                   return Task.FromResult(0);
               }
           }
           return Task.FromResult(0);
       }
   }
});

引用自:https://stackoverflow.com/questions/34997674