Identity Server 3 - 401 on Ajax Calls instead of 302
In your example the UseCookieAuthentication
no longer controls this, instead the UseOpenIdConnectAuthentication
does. This involves using the Notifications
property and intercepting OpenID Connect authentication requests.
Try out the following for inspiration:
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); } }});
In my case the IsAjaxRequest did not do the trick. Instead I rely on all routes to the WebAPI being under "/api", so instead of the IsAjaxRequest I do:
RedirectToIdentityProvider = context => { if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication){ if (context.Request.Path.StartsWithSegments(new PathString("/api")) && context.Response.StatusCode == (int)HttpStatusCode.Unauthorized){ context.HandleResponse(); return Task.CompletedTask; } } return Task.CompletedTask;}