Search code examples
c#asp.netasp.net-coreasp.net-identityasp.net-core-mvc

ASP.NET core, change default redirect for unauthorized


I am attempting to redirect to a different login url in ASP.NET MVC6

My account controller login method has a Route attribute to change the url.

[HttpGet]
[AllowAnonymous]
[Route("login")]
public IActionResult Login(string returnUrl = null)
{
    this.ViewData["ReturnUrl"] = returnUrl;
    return this.View();
}

When attempting to access an unathorized page, I am redirected to the invalid url, it should just be /login but instead I get http://localhost/Account/Login?ReturnUrl=%2Fhome%2Findex

I have configured the cookie authentication path as follows:

services.Configure<CookieAuthenticationOptions>(opt =>
{
    opt.LoginPath = new PathString("/login");
});

I have added a default filter, to ensure that all urls require authentication by default.

services.AddMvc(
    options =>
    {
        options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
    });

I have checked that the url /login does in fact load the login page, whilst /account/login does not, as expected.

edit: I have left the routes as is, (apart from changing the default controller and action)

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "default",
      template: "{controller=Site}/{action=Site}/{id?}");
});

Solution

  • 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.