Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second sign-in causes infinite redirect loop after the first successful login MVC .NET 5 OWIN ADAL OpenIDConnect

first post so be gentle! :)

I'm developing an MVC .NET 5 web app for Office 365 and am using the OpenIDConnect framework. I have set up OWIN (3) and ADAL(2) and my Azure AD Application. There is no user actioned login, the home controller has an [Authorize] attribute attached, forcing the immediate login redirect to Azure AD. I am not using roles in any of my Authorize attributes.

The Problem: I can log in to my applications successfully - ONCE! After the first login, I close the browser (or open a new browser on a different machine) and I hit the app again. It redirects me to the Azure AD login screen which I sign into and then it continuously redirects between the app and Azure until I get the infamous 400 headers to long issue. Looking into the cookie store, I find that it's full of nonces. I check the cache (Vittorio's EFADALCache recipe, although I was using the TokenCache.DefaultShared when this problem was discovered) and it has hundreds of rows of cache data (Only one row generated with a successful sign in).

I can see as the redirects occur via the output window that a new access and refresh token is being generated each round trip:

Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - AcquireTokenByAuthorizationCodeHandler: Resource value in the token response was used for storing tokens in the cache
iisexpress.exe Information: 0 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - AcquireTokenByAuthorizationCodeHandler: Resource value in the token response was used for storing tokens in the cache
Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 31/07/2015 12:31:52:  - TokenCache: Deserialized 1 items to token cache.
iisexpress.exe Information: 0 : 31/07/2015 12:31:52:  - TokenCache: Deserialized 1 items to token cache.
Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - TokenCache: Storing token in the cache...
iisexpress.exe Information: 0 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - TokenCache: Storing token in the cache...
Microsoft.IdentityModel.Clients.ActiveDirectory Verbose: 1 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - TokenCache: An item was stored in the cache
iisexpress.exe Information: 0 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - TokenCache: An item was stored in the cache
Microsoft.IdentityModel.Clients.ActiveDirectory Information: 2 : 31/07/2015 12:31:52: 15ad306e-e26d-4827-98dc-dea75853788a - AcquireTokenHandlerBase: === Token Acquisition finished successfully. An access token was retuned:
    Access Token Hash: PN5HoBHPlhhHIf1lxZhEWb4B4Hli69UKgcle0w7ssvo=
    Refresh Token Hash: 3xmypXCO6MIMS9qUV+37uPD4kPip9WDH6Ex29GdWL88=
    Expiration Time: 31/07/2015 13:31:51 +00:00
    User Hash: GAWUtY8c4EKcJnsHrO6NOzwcQDMW64z5BNOvVIl1vAI=

The AuthorizationCodeReceived notification in my OpenIdConnectAuthenticationOptions is being hit when the problem is happening, so I know that Azure thinks the login was successful (or else the redirect back to the app wouldn't occur):

    private static void PrepO365Auth(IAppBuilder app)
    {

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        //Configure OpenIDConnect, register callbacks for OpenIDConnect Notifications
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {

                ClientId = ConfigHelper.ClientId,
                Authority = authority,
                PostLogoutRedirectUri = "https://localhost:44300/Account/SignedOut",
                RedirectUri = "https://localhost:44300/",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        AuthenticationContext authContext = new AuthenticationContext(authority, new EFADALTokenCache(signedInUserID)); // TokenCache.DefaultShared Probably need a persistent token cache to handle app restarts etc
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, ConfigHelper.GraphResourceId);

                        return Task.FromResult(0);
                    },

                    AuthenticationFailed = context =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                        return Task.FromResult(0);
                    }
                }
            });
    }
}

I have replaced (after discovering the problem) the Authorized attribute with my own Auth attribute, inheriting from AuthorizeAttribute, just so I could try and step into the Authorize code and see what's happening. I built a PDB file from the version 5 version of MVC 5's source code, but all that happens is that it jumps back into my own code :( That being said, I've overridden what I could and have found that filterContext.HttpContext.User.Identity.IsAuthenticated is false, which makes sense, as that would cause the redirect back to Azure sign in.

So, I know that:

  • Azure is accepting my login and returning the relevant tokens
  • On the second login, before OnAuthorization, the filterContext.HttpContext.User.Identity.IsAuthenticated is returning false
  • my Azure Application configuration is fine, or it wouldn't authenticate at all

I think that:

  • There is something in the MVC Identity setup that is wrong. Azure is working correctly or it wouldn't authenticate at all.
  • It's not a cookie issue as the problem arises if you carry out the second login on a different machine

I'm sorry this is a bit long winded, but there are so many of these infinite redirect issues out there, I needed to explain why my situation was different!

What I'm looking for (if not an answer!) is a push in the right direction as to how I can debug further.

Appreciate any help you can give!

Andy

like image 530
Andy Bullivent Avatar asked Jul 31 '15 13:07

Andy Bullivent


2 Answers

Have found the answer for anyone interested. It's a known bug in Katana where the Katana cookie manager and the ASP .NET cookie manager clash and overwrite each other's cookies. Full details and workaround here:

http://katanaproject.codeplex.com/wikipage?title=System.Web%20response%20cookie%20integration%20issues&referringTitle=Documentation

The SystemWebCookieManager shown below can now be found in the Microsoft.Owin.Host.SystemWeb Nuget package.

Adding the code for when CodePlex dies:

//stick this in public void ConfigureAuth(IAppBuilder app)
  app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                // ...
                CookieManager = new SystemWebCookieManager()
            });

//And create this class elsewhere:
public class SystemWebCookieManager : ICookieManager
    {
        public string GetRequestCookie(IOwinContext context, string key)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            var cookie = webContext.Request.Cookies[key];
            return cookie == null ? null : cookie.Value;
        }

        public void AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

            bool domainHasValue = !string.IsNullOrEmpty(options.Domain);
            bool pathHasValue = !string.IsNullOrEmpty(options.Path);
            bool expiresHasValue = options.Expires.HasValue;

            var cookie = new HttpCookie(key, value);
            if (domainHasValue)
            {
                cookie.Domain = options.Domain;
            }
            if (pathHasValue)
            {
                cookie.Path = options.Path;
            }
            if (expiresHasValue)
            {
                cookie.Expires = options.Expires.Value;
            }
            if (options.Secure)
            {
                cookie.Secure = true;
            }
            if (options.HttpOnly)
            {
                cookie.HttpOnly = true;
            }

            webContext.Response.AppendCookie(cookie);
        }

        public void DeleteCookie(IOwinContext context, string key, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            AppendResponseCookie(
                context,
                key,
                string.Empty,
                new CookieOptions
                {
                    Path = options.Path,
                    Domain = options.Domain,
                    Expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
                });
        }
    }

I made a gist of it, too: https://gist.github.com/irwinwilliams/823f43ef8a5e8019a95874049dbb8b00

like image 199
Andy Bullivent Avatar answered Oct 18 '22 08:10

Andy Bullivent


I encountered this issue and applied ALL THE FIXES ON THE INTERNET. None of them worked, then I went in and looked at my cookie. It was huge. Owin middleware was truncating it and then then [Authorize] attribute wasn't able to verify the identity -> send user to oidc -> identity good -- redirect to client -> truncate cookie -> can't verify in [Authorize] -> send user to oidc -> etc.

The fix was in Microsoft.Owin.Host.SystemWeb 3.1.0.0 and using the SystemWebChunkingCookieManager.

It'll split the cookies and parse them together.

  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
      AuthenticationType = "Cookies",
      CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
  });
like image 9
Scott Belchak Avatar answered Oct 18 '22 07:10

Scott Belchak