Azure OpenID Connect via OWIN Middleware resulting in Infinite Redirect Loop
Asked Answered
A

5

14

I have setup OpenID Connect authentication in my ASP.NET MVC application using OWIN Middleware.

As this Fiddler output shows, once successfully logging in via Azure OpenID Connect, the browser continually loops back and forth between my site.azurewebsites.net and login.windows.net.

Fiddler loop

I have ensured following keys are correctly matching Azure AD information

<add key="ida:AADInstance" value="https://login.windows.net/{0}" />
<add key="ida:Tenant" value="******.onmicrosoft.com" />
<add key="ida:ClientId" value="*******" />
<add key="ida:PostLogoutRedirectUri" value="*********" />

And my Start.cs code is as follows

 private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

    private string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

    IAuthorizationService authorizationService = new AuthorizationService();

    public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {

            ExpireTimeSpan =TimeSpan.FromMinutes(15)
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri}
            });
    }
}

Not sure what is causing this to constantly redirect. I have placed an [Authorize] attribute on the MVC Controller where Post Authentication Redirect Url goes.

Acerbic answered 17/12, 2014 at 12:23 Comment(6)
are you initially hitting the website on http only? not https? i have the same scenario where if i hit the website with http only, i get redirected to login, gets authenticated, redirected back and ends up in a loop. ended up forcing https.Fransiscafransisco
Everything is being accessed on HTTPS.Acerbic
Did you ever find a solution to your problem? I am having a similar issue. The answer below did not help.Kemme
Did not find a solution to this so ended up abandoning Open ID Connect. I am now using ASP.NET Identity to authenticate against Azure AD. Have a look at this rickrainey.com/2014/08/19/…Acerbic
See also #31589052 for a similar problemSedan
Im also having the same issue. Redirect loop. Https or httpCellarage
C
4

I ran into this issue last night in an ASP.NET Framework 4.5.1 MVC app. There were two issues for me.

  1. Trying to access the site using HTTP instead of HTTPS

    • I have localhost, dev, and test (and prod of course) environments running under HTTPS so I didn't have to worry about handling HTTP locally. I have HSTS running everywhere and that solved this problem. See Best way in asp.net to force https for an entire site? for additional info.
  2. Cookie overwriting as described here https://github.com/aspnet/AspNetKatana/wiki/System.Web-response-cookie-integration-issues

    • What worked for me was the Reconfigure the CookieAuthenticationMiddleware to write directly to System.Web's cookie collection fix combined with Katana 3.1.0 has several implementations of ICookieManager available. Older versions can use the following fix.

I was a "I tried everything but nothing works" dev until I found that fix. Hopefully that works for you too.

Cadel answered 8/3, 2019 at 19:6 Comment(2)
I updated my URL Rewrite based on the link provided.Replevin
For me the redirect loop appeared to be caused by the conflict between OWIN and System.Web decribed here: System.Web response cookie integration issues. I added CookieManager = new SystemWebCookieManager() to both UseCookieAuthentication and ` UseOpenIdConnectAuthentication` and seems to have resolved the issue.Georgia
A
1

what is happening here is related to what JuneT noticed. This is related to the default on CookieAuthenticationOptions.CookieSecure == CookieSecureOption.SameAsRequest. Since you started at http, the final redirect is to http. The request that created the 'authcookie' was https from AAD.

I was able to get this working by setting CookieSecure == CookieSecureOption.Always. This means that cookie could leak along with your auth.

Is there must be a way to ensure that pages that auth only will accept connections on https.

Advisee answered 18/12, 2014 at 4:55 Comment(1)
i forced mine via this (note, in my case i want entire site in https): <rewrite> <rules> <rule name="Force HTTPS" enabled="true"> <match url="(.*)" ignoreCase="false" /> <conditions> <add input="{HTTPS}" pattern="off" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" appendQueryString="true" redirectType="Permanent" /> </rule> </rules> </rewrite>Fransiscafransisco
F
1

To resolve this issue: you can upgrade your application to use ASP.NET Core. If you must continually stay on ASP.NET, perform the following: Update your application’s Microsoft.Owin.Host.SystemWeb package be at least version. Modify your code to use one of the new cookie manager classes, for example something like the following:

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationType = "Cookies", 
    CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager() 
});

Reference Link

Flintlock answered 29/3, 2020 at 5:7 Comment(0)
C
0

Fixed this issue by ensuring that request is using https BEFORE redirecting to Azure

            app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = AppConfig.ClientId,
                Authority = AppConfig.Authority,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = context =>
                       {
                           if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                           {
                               // ensure https before redirecting to Azure
                               if (!context.Request.IsSecure)
                               {
                                   context.Response.Redirect(string.Format("https://{0}{1}", context.Request.Uri.Authority, context.Request.Uri.AbsolutePath));
                                   context.HandleResponse();
                                   return Task.FromResult(0);
                               }
                           }

                           return Task.FromResult(0);
                       },

                    AuthenticationFailed = context =>
                                    {
                                        context.HandleResponse();
                                        context.Response.Redirect(AppConfig.RedirectUri + "SignInError?message=" + context.Exception.Message);
                                        return Task.FromResult(0);
                                    },
                },
            });
Carolynncarolynne answered 25/10, 2016 at 19:30 Comment(0)
I
0

I faced the same issue and fixed it by using nuget package kentor.owincookiesaver. Use code as below:-

public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseKentorOwinCookieSaver();//Workaround for infinite loop between webapp & login page

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
}
Isabeau answered 17/2, 2017 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.