Search code examples
c#asp.net-coreasp.net-core-mvcauthorize-attributecookie-authentication

AuthorizeAttribute redirecting to an incorrect url when deployed to a website with a subdomain


Normally (on my localhost for example), [Authorize] correctly redirects to LoginPath specified in the CookieAuthenticationOptions.

However, when I deploy to my staging site (staging.mysite.com), the authorize redirection seems to misplace part of the url. In my case, it is going to:

http://staging/Account.mysite.com/Login?ReturnUrl=%2FHome%2FAuthorize

when it should be going to:

http://staging.mysite.com/Account/Login?ReturnUrl=%2FHome%2FAuthorize

The app is very basic:

//Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
   .AddCookie(options =>
   {
       options.LoginPath = "/Account/Login";
       options.LogoutPath = "/Account/Logout";
       options.AccessDeniedPath = "/Home/Unauthorized";
       options.ReturnUrlParameter = "ReturnUrl";
   });

services.AddMvc()

//....

app.UseMvc();

My controllers:

//HomeController.cs
[Route("[controller]/[action]")]
public class HomeController : Controller
{
    [Authorize]
    public IActionResult Authorize()
    {
        return Ok("You are authorized");
    }
}

//AccountController.cs
[Route("[controller]/[action]")]
public class AccountController : Controller
{
    public IActionResult Login()
    {
        return View(new LoginViewModel());
    }
}

Anyone see where I'm going wrong?


UPDATE:

Strangely, if I do the changes below, it works. So it seems the issue is with having the action specified in the route?

options.LoginPath = "/Login"; //I removed /Account


[HttpGet("/Login")] //I added the "/Login" template
public IActionResult Login()

Solution

  • Found the issue.

    The problem was not with asp.net core or my app.

    The issue was with a redirect regex we were using in IIS.