JavaScriptServices icon indicating copy to clipboard operation
JavaScriptServices copied to clipboard

Redirect loop with Identity, SPA, and [Authorize] on Home/Index

Open jimsmart opened this issue 9 years ago • 4 comments

Hi,

There is something cranky going on with MapSpaFallbackRoute (ASP.NET Core 1.1.2) when used with Identity (1.1.2), with a HomeController Index using the [Authorize] tag — which causes infinite redirects when Kestrel receives an HTTP HEAD command.

The problem goes away if I remove either the MapSpaFallbackRoute (not helpful: the app is a SPA), or if I remove the [Authorize] tag from the HomeController's Index method.

Note that the problem doesn't manifest with a common HTTP GET/POST, so it was particularly difficult to track down the exact cause/combination for this to manifest.

To reproduce:

Using VS create a new ASP.NET Core project with Identity (Individual User Accounts). Add Microsoft.AspNetCore.SpaServices (1.1.1), wait for restore to complete.

Modify Startup.cs to add appropriate routes.MapSpaFallbackRoute call:-

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

		routes.MapSpaFallbackRoute(
			name: "spa-fallback",
			defaults: new { controller = "Home", action = "Index" });

		});

Modify HomeController.cs to require auth on Index:-

        [Authorize]
	public IActionResult Index()
        {
            return View();
        }

Start the project dotnet run

From a terminal, run:

$ curl --verbose -s --max-redirs 3 --location http://localhost:5000/ 1> /dev/null

The output will be something like:

*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> GET / HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:03:03 GMT
< Content-Length: 0
< Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2F
< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5000/Account/Login?ReturnUrl=%2F'
* Found bundle for host localhost: 0x7fc088c10240
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 5000 (#0)
> GET /Account/Login?ReturnUrl=%2F HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Wed, 26 Jul 2017 21:03:06 GMT
< Content-Type: text/html; charset=utf-8
< Server: Kestrel
< Cache-Control: no-cache
< Pragma: no-cache
< Transfer-Encoding: chunked
< Expires: -1
< Set-Cookie: Identity.External=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/
< Set-Cookie: .AspNetCore.Antiforgery.3zWvHPcpM08=CfDJ8Gys1JZsiDFNtRmGgYLfzaE5yxjO-BBs8Tgl95dBaNZFOlg2UFpZ7kpet6YN6hpbHek-92cXtvMvhBI5kb3p5F8Kfc4iERJ-HGgUqymROx8lULcpQxMbueqK0XhNRQbgueqK5DggwJXzXLWgebyeuG8; path=/; httponly
< X-Frame-Options: SAMEORIGIN
< 
{ [1031 bytes data]
* Connection #0 to host localhost left intact

All is good.

Now run:

curl --verbose --max-redirs 3 --head --location http://localhost:5000/

See the redirect loop:

   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> HEAD / HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:04:07 GMT
Date: Wed, 26 Jul 2017 21:04:07 GMT
< Server: Kestrel
Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2F
Location: http://localhost:5000/Account/Login?ReturnUrl=%2F

< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5000/Account/Login?ReturnUrl=%2F'
* Found bundle for host localhost: 0x7fea53c0fe90
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 5000 (#0)
> HEAD /Account/Login?ReturnUrl=%2F HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:04:07 GMT
Date: Wed, 26 Jul 2017 21:04:07 GMT
< Server: Kestrel
Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252F
Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252F

< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252F'
* Found bundle for host localhost: 0x7fea53c0fe90
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 5000 (#0)
> HEAD /Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252F HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:04:07 GMT
Date: Wed, 26 Jul 2017 21:04:07 GMT
< Server: Kestrel
Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252F
Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252F

< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252F'
* Found bundle for host localhost: 0x7fea53c0fe90
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 5000 (#0)
> HEAD /Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252F HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:04:07 GMT
Date: Wed, 26 Jul 2017 21:04:07 GMT
< Server: Kestrel
Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252F
Location: http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252F

< 
* Connection #0 to host localhost left intact
* Maximum (3) redirects followed
curl: (47) Maximum (3) redirects followed

If you move the [Authorize] tag to e.g. About() instead, and change the urls in the curl command, everything works fine: single redirects as expected.

If you remove the call to MapSpaFallbackRoute in Startup.cs, everything works fine: single redirects as expected.

But the combination of [Authorize] on HomeController.Index() and the call to MapSpaFallbackRoute manifests the problem.

We're actually seeing this in the wild — we have a SPA app served via Home/Index, on a site that requires auth on all pages, and some machines in the office simply get a 'too many redirects' error when trying to even access the login page (which should have no redirects). I've no idea why they're issuing a HEAD command (or indeed if they actually are? I suspect the same problem manifests in other ways also, just not with a simple GET/POST/etc) — but I've finally reproduced the infinite redirect on a dev machine with a simple configuration and trigger. (I'm sure you can imagine how long this may have taken me to pin down!?)

FWIW, the server log for the bad case is:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.Index (IdentityTest) in 0.143ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.4784ms 302 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/Account/Login?ReturnUrl=%2F  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.Index (IdentityTest) in 0.1167ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.2853ms 302 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252F  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.Index (IdentityTest) in 0.1098ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.3312ms 302 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252F  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.Index (IdentityTest) in 0.1342ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 0.3521ms 302 

To my less knowledgeable mind, it's like some middlewear is kicking in when it shouldn't, but IDK.

Is there something we are missing? Or is this combination of Identity, SpaServices and [Authorize] on HomeController.Index just subtly broken for anything beyond GET/POST?

Perhaps this bug report belongs with Identity? Or Kestrel? (No end of googling sheds any light on the matter)

— Is there a workaround?

Obviously we have no control over whatever it is these few browsers are doing — FWIW, the app is over HTTPS (despite this repro not using it at all) so I'm fairly sure it's not firewalls/antivirus/proxies.

Obviously(?) we can't remove the MapSpaFallbackRoute (or can we? Suggestions for routing workarounds are most welcome!)

And we don't particularly want to serve the app from anything but the root url — and the app/homepage must require authentication.

jimsmart avatar Jul 26 '17 21:07 jimsmart

FWIW, this is what you get if you remove [Authorize] from Index() and put it on About() instead — it works as expected.

$ curl --verbose --max-redirs 3 --head --location http://localhost:5000/Home/About
*   Trying ::1...
* Connected to localhost (::1) port 5000 (#0)
> HEAD /Home/About HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 302 Found
HTTP/1.1 302 Found
< Date: Wed, 26 Jul 2017 21:52:29 GMT
Date: Wed, 26 Jul 2017 21:52:29 GMT
< Server: Kestrel
Server: Kestrel
< Location: http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout
Location: http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout

< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout'
* Found bundle for host localhost: 0x7fa160f01320
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (::1) port 5000 (#0)
> HEAD /Account/Login?ReturnUrl=%2FHome%2FAbout HTTP/1.1
> Host: localhost:5000
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Date: Wed, 26 Jul 2017 21:52:31 GMT
Date: Wed, 26 Jul 2017 21:52:31 GMT
< Content-Type: text/html; charset=utf-8
Content-Type: text/html; charset=utf-8
< Server: Kestrel
Server: Kestrel

< 
* Connection #0 to host localhost left intact

Server log

nfo: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/Home/About  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.About (IdentityTest) in 75.9936ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 570.8271ms 302 
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 HEAD http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout  
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method IdentityTest.Controllers.HomeController.Index (IdentityTest) with arguments ((null)) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor[1]
      Executing ViewResult, running view at path /Views/Home/Index.cshtml.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action IdentityTest.Controllers.HomeController.Index (IdentityTest) in 2815.1756ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 2842.0962ms 200 text/html; charset=utf-8

I'd expect to see something similar to this with [Authorize] on Index — infinite redirects doesn't strike me as particularly sane behaviour.

jimsmart avatar Jul 26 '17 21:07 jimsmart

Thanks for providing clear repro steps.

What happens is:

  1. Browser makes HEAD request to /
    • [Authorize] middleware returns a 302 redirection to /Account/Login?ReturnUrl=%2F
  2. Browser makes HEAD request to /Account/Login?ReturnUrl=%2F
    • The default template includes two Login actions on AccountController. One of them is marked with [HttpGet]; the other with [HttpPost]. Therefore, neither of them accepts HEAD requests. And so no routes match the incoming request.
    • The MapSpaFallbackRoute middleware sees that no routes have matched, so it thinks you want to serve your SPA. It marks the request to be handled by the fallback route you've configured, i.e., { controller = "Home", action = "Index" }.
    • But that action has an [Authorize], which returns a 302 redirection to /Account/Login?ReturnUrl=%2F...etc.
  3. Go to step 2 and loop infinitely.

So the basic issue is that your Login action does not accept HEAD requests. If you're using MapSpaFallbackRoute, you really don't want to be in a situation where your fallback route issues redirections to an action that can return 404, because that creates this infinite loop scenario.

A quick fix for you would be to either add [HttpHead] to the Login action on your AccountController, or to remove the [HttpGet] restriction from the first one of them (but keep [HttpPost] on the other).

Longer term, we'll consider whether we should change the default template in one of those ways. Thanks for reporting it!

SteveSandersonMS avatar Jul 27 '17 11:07 SteveSandersonMS

Thank you very much for the prompt workarounds Steve — I went with removing the [HttpGet] from the Login action, so it can act as a 'black hole' for any incoming requests, as this makes the most sense to me.

Regards, /Jim

jimsmart avatar Jul 27 '17 12:07 jimsmart

I have a similar issue. It seems that the home controller breaks whenever you add anything that calls an external site before the prerender function begins. I tried to over come it by creating an api on the current site and calling that from angular; but that also breaks the site by causing the redirect loop. Is there a routing bug with this recipe?

ddineen avatar Oct 15 '17 08:10 ddineen