Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to login when unauthorized in ASP.NET Core

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?

like image 694
grokky Avatar asked Oct 24 '16 11:10

grokky


People also ask

How to redirect to login page if not logged in ASP net?

The Login page URL will be set in the authentication section of the Web. Config file and the User will be redirected back to Login page if not logged in using the Authorize Data Annotation attribute in ASP.Net MVC Razor.

What does HttpContext SignInAsync do?

SignInAsync(HttpContext, String, ClaimsPrincipal, AuthenticationProperties) Sign in a principal for the specified scheme.


1 Answers

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.

like image 133
animalito maquina Avatar answered Sep 28 '22 06:09

animalito maquina