skip to Main Content

I have a fairly standard setup that involves an ASP.NET Core app that is hosted by an Azure App Service, proxied through Cloudflare.

This extension method is called after the usual boilerplate ASP.NET Core identity code, which also configures cookies:

internal static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder authenticationBuilder, IConfiguration config)
{
    void configureMicrosoftIdentityOptions(OpenIdConnectOptions options)
    {
        options.Authority = config["xxx:Authority"];
        options.ClientId = config["xxx:ClientId"];
        options.ClientSecret = config["xxx:ClientSecret"];
        options.SignInScheme = IdentityConstants.ApplicationScheme;
        options.ResponseType = OpenIdConnectResponseType.IdToken;
        options.Prompt = "select_account";
    
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidAudience = config["xxx:ClientId"],
        };
    };

    return authenticationBuilder.AddOpenIdConnect("AzureAD", configureMicrosoftIdentityOptions);
}

public static AuthenticationBuilder AddCookieLogin(this AuthenticationBuilder authenticationBuilder)
{
    void configureCookieAuthOptions(CookieAuthenticationOptions options)
    {                
        options.Cookie.Name = "MyApp";
        options.Cookie.IsEssential = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.ExpireTimeSpan = TimeSpan.FromDays(1);
        options.SlidingExpiration = true;
        options.LoginPath = "/signin";
    }

    return authenticationBuilder.AddCookie(configureCookieAuthOptions);
}

The entire process is kicked off in a simple controller action:

return Challenge(new AuthenticationProperties { RedirectUri = "/" }, scheme);

Nothing special to report in the Azure AD App Registration. The redirect URI is set to {MYURIHERE}/signin-oidc. This all works jolly well locally. In my logs, I find that Azure AD does comes back to the app and signs in the user (‘AuthenticationScheme: xxx signed in.’) and redirects from the signin-oidc endpoint to the requested redirect URI.

With the proxy enabled on the Azure App Service, however, ‘sometimes’ it happens that the browser seems to be stuck after logging into Azure AD. This is the URL in question that freezes until a timeout is thrown:

https://login.microsoftonline.com/common/reprocess?ctx=xxx0&sessionid=yyy

The logs still indicate ‘AuthenticationScheme: xxx signed in.’ but stop logging after this entry: Request finished HTTP/1.1 POST XXX/signin-oidc - 302 0 - 1014.6661ms

For some unknown reason, hitting CTRL + F5 before starting the Azure AD authentication process seems to fix it. I’ve tried all sorts of combinations to set the cookies just so and even gone so far as to set ‘"Clear-Site-Data’ headers before the login page loads.

To no avail, so I am out of ideas and would like to know if there is anything else I could try. The odd thing is that another ASP.NET Core web app, which uses the built-in authentication methods on Azure, doesn’t have this problem as it also happens to be proxied by Cloudflare. So it definitely seems to be an issue in my code rather than Cloudflare, Azure App Service, or anything else.

UPDATE 2023-10-16

In a desperate attempt, I scrapped the code above and swapped AddOpenIdConnect with AddMicrosoftAccount. The result is the same, but now the browser freezes on the https://login.microsoftonline.com/common/oauth2/v2.0/authorize page. At the bottom left corner of Edge, there’s a box that says ‘waiting for MYREDIRECTURIDOMAIN.com’.

2

Answers


  1. Chosen as BEST ANSWER

    While everybody else was just downvoting the ChatGPT-generated answer, I've come to my own rescue. The desperate attempt led me to believe that it solved the problem.

    I replaced AddOpenIdConnect with AddMicrosoftAccount with the following configuration:

    options.ClientId = config["ClientId"];
    options.ClientSecret = config["ClientSecret"];                
    options.Events = new OAuthEvents()
    {
        OnTicketReceived = OAuthEventHandlers.OnTicketReceived(ClaimTypes.Email),
        OnRedirectToAuthorizationEndpoint = ctx =>
        {
            ctx.HttpContext.Response.Redirect(ctx.RedirectUri + "&prompt=select_account");
            return Task.CompletedTask;
        }
    };
    

    Forwarded headers:

    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();
    });
    
    

    At some I also had specified XForwardedHost but it seems to work without (and maybe because of that, who knows).

    Cookie auth options:

    options.Cookie.IsEssential = true; 
    options.Cookie.HttpOnly = true;                
    options.Cookie.SameSite = SameSiteMode.None;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    

    No idea if is this is fireproof, but it seems to be working for now.


  2. Based on the code and information you provided, it seems like you are experiencing an issue with the Azure AD login process getting stuck when accessing your application through the Azure App Service with Cloudflare as a proxy.

    One possible reason for this behavior could be related to how authentication cookies are handled between the Azure AD login flow and Cloudflare. Cloudflare may interfere with the cookie handling and cause the login process to freeze.

    To troubleshoot this issue, you can try the following suggestions:

    Bypass Cloudflare: Temporarily disable Cloudflare’s proxy for your application and see if the Azure AD login process works correctly without it. This will help determine if Cloudflare is causing the issue.

    Check Cookie Configuration: Review your cookie configuration and ensure that it aligns with the requirements of Azure AD and Cloudflare. Make sure the cookie names, paths, and settings are consistent and compatible.

    Validate Redirect URIs: Double-check the redirect URIs configured in your Azure AD App Registration. Ensure that they match the correct URIs used by your application, including any prefixes or suffixes added by Cloudflare.

    Inspect Network Traffic: Use browser developer tools or a tool like Fiddler to inspect the network traffic during the login process. Look for any unusual requests, redirects, or errors that might provide additional insights into the issue.

    Review Cloudflare Settings: Check your Cloudflare settings, especially regarding caching, security features, and page rules. Some configurations may interfere with the authentication flow.

    Upgrade Azure AD SDK: Make sure you are using the latest version of the Azure AD SDK and related dependencies. Upgrading to the latest version may resolve any known issues or compatibility problems.

    Contact Azure Support: If none of the above steps solve the problem, consider reaching out to Microsoft Azure support. They can provide further guidance and assistance specific to Azure App Service and Azure AD integration.

    Please note that troubleshooting such issues can be complex, and it may require additional investigation beyond the provided information.

    David Lucas from Upwork

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search