Redirect to login when unauthorized in ASP.NET Core

81,601

Solution 1

You can configure the path using CookieAuthenticationOptions class.

Something like this.

app.UseCookieAuthentication(new CookieAuthenticationOptions {
        LoginPath = new PathString("/Login/"),
        AuthenticationType = "My-Magical-Authentication",
        // etc...
        },
});

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 5

this code block in the startup file works for me in .Net Core 3.1

services.ConfigureApplicationCookie(options =>
    {
        // Cookie settings
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

        options.LoginPath = "/Identity/Account/Login";
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";
        options.SlidingExpiration = true;
    });

Share:
81,601
grokky
Author by

grokky

Updated on July 09, 2022

Comments

  • grokky
    grokky almost 2 years

    In the previous ASP.NET MVC, there was an option to redirect to the login action, if the user was not authenticated.

    I need the same thing with ASP.NET Core, so I:

    1. created a ASP.NET Core project from the Visual Studio template
    2. added [Authorize] to some arbitrary action
    3. opened the corresponding view in my browser

    I don't expect a redirect because I haven't configured it. BUT, it automatically redirects to the login action!

    Where/how is this option set?

  • grokky
    grokky over 7 years
    I saw that in this article, but that says "Using Cookie Middleware without ASP.NET Core Identity". I am using Identity.
  • grokky
    grokky over 7 years
    Also, I not only want to control this setting, I want to understand where/how it is happening. I don't understand how it knows to find my login view. That is what I want to understand.
  • Anuraj
    Anuraj over 7 years
    Please look into this code - github.com/aspnet/Security/blob/dev/src/…
  • Wouter
    Wouter almost 7 years
    Works fine for me in version 1.1.0 (July 2017)
  • susieloo_
    susieloo_ almost 7 years
    Anton / @Wouter, are you guys using .NETCore?
  • Wouter
    Wouter almost 7 years
    Using .net core 1.1
  • Alexander
    Alexander almost 5 years
    @Anuraj link is dead, you know the new one?
  • Igor Mikushkin
    Igor Mikushkin over 4 years
    I would like to add that ConfigureApplicationCookie should be placed after AddIdentity. Otherwise it has no effect.
  • c_Reg_c_Lark
    c_Reg_c_Lark about 4 years
    Where in the pipeline call stack did you place this?
  • Serj Sagan
    Serj Sagan about 4 years
    It should be the first one or one of the first, but certainly before app.UseMvc
  • conterio
    conterio almost 4 years
    did the trick for me. using asp.net core 3.1 mvc proj, thanks
  • Sayyed Dawood
    Sayyed Dawood about 3 years
    In 2.0 and later versions: If you want to tweak Identity cookies, they're no longer part of IdentityOptions. Rather we have to use ConfigureApplicationCookie method. Such as services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn"); for more, see here: docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/…