Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?}"); }); 
like image 245
Jim Avatar asked Feb 08 '17 05:02

Jim


1 Answers

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.

like image 151
mxmissile Avatar answered Oct 11 '22 18:10

mxmissile