Redirect to login when unauthorized in ASP.NET Core
For anyone that's interested it can also be done with the AddIdentity service provider.
services.AddIdentity<User, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
options.Cookies.ApplicationCookie.AutomaticChallenge = true;
options.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
})
.AddEntityFrameworkStores<MehandiContext>()
.AddDefaultTokenProviders();
And as explained here: https://stackoverflow.com/a/41643105/5784635
I attempted this in April 2017 and "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0"
doesn't redirect I had to use the 1.0.1
version
You can configure the path using CookieAuthenticationOptions
class.
Something like this.
app.UseCookieAuthentication(new CookieAuthenticationOptions {
LoginPath = new PathString("/Login/"),
AuthenticationType = "My-Magical-Authentication",
// etc...
},
});
With the current aspnet core version (2.1.0), this has changed, now you can use the extensions:
services.ConfigureApplicationCookie(options => options.LoginPath = "/login");
or
services
.AddAuthentication()
.AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/logout";
});
You can see more about migrating in to 2.0 in this article.
The redirect did not work in my app at all and none of the solutions here fixed it, but using Status Code Pages
did:
app.UseStatusCodePages(async context =>
{
var response = context.HttpContext.Response;
if (response.StatusCode == (int)HttpStatusCode.Unauthorized ||
response.StatusCode == (int)HttpStatusCode.Forbidden)
response.Redirect("/Authentication");
});
app.UseMvc(...