Reputation: 324
I use ASP.NET Core for an api and can not find a way to configure identity to return a 401 instead of redirecting to the login page. I use the IdentityServerAuthentication Middleware.
In the Startup.cs, I give these options:
var options = new IdentityServerAuthenticationOptions
{
Authority = Configuration.GetConnectionString("Authority"),
ScopeName = "scopeName",
RequireHttpsMetadata = false,
};
app.UseIdentityServerAuthentication(options);
Upvotes: 3
Views: 2095
Reputation: 51
To overwrite the default behavior redirecting to identity server when unauthorized, we had to create a custom Authorize class implementing System.Web.MVC.AuthorizeAttribute
. Then, in the case that the user was unauthorized (but logged in via identity server) we showed the user an unauthorized page.
protected override void HandleUnauthorizedRequest(AuthorizationContext
filterContext)
{
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
//Intercept results where person is authenticated but still doesn't have
permissions
if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult(ConfigSettings.KPToolsURL +
"/Error/HttpError401");
return;
}
base.HandleUnauthorizedRequest(filterContext);
}
I wrote a blog post about it in which I go into more detail https://spin.atomicobject.com/2018/07/09/identityserver-auth-mvc/.
Upvotes: 0
Reputation: 324
I find a solution, In the request, you can add a header X-Requested-With with a value of XMLHttpRequest. This will tell identity to not redirect to the login page.
Upvotes: 8