ASP.NET core, change default redirect for unauthorized
You may also want to try using StatusCodePages
:
app.UseStatusCodePages(async contextAccessor =>
{
var response = contextAccessor.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
{
response.Redirect("/Error/Unauthorized");
}
});
If you check UseIdentity
extension method here you will notice that it is using IdentityOptions
not CookieAuthenticationOptions
, so instead you must configure IdentityOptions
:
services.Configure<IdentityOptions>(opt =>
{
opt.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
});
Edit
For asp.net core 2.0: Identity cookie options are no longer part of IdentityOptions. Check mxmissile's answer.
With asp.net core 2.0
out now, this has changed to:
services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn");
More on migrating to 2.0 here. And even more information on migrating from 2.0 to 2.1.
Since asp.net core 2.0
if you use cookies without Identity:
app.UseAuthentication();
// If you don't want the cookie to be automatically authenticated and assigned HttpContext.User,
// remove the CookieAuthenticationDefaults.AuthenticationScheme parameter passed to AddAuthentication.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/LogIn";
options.LogoutPath = "/Account/LogOff";
});
source