59

I getting this error when a Azure AD user login (I able to get the user´s claims after), im using a combination of OpenIdConnect, with asp.net Identity core over net.core 2.0

An unhandled exception occurred while processing the request. Exception: Correlation failed. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext()

The trace:

Exception: Correlation failed. Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+d__12.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()

Correlation Failed

Here is my Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BPT.PC.IdentityServer.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>(options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services.AddMvc();
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("AzureAD", opts =>
            {
                Configuration.GetSection("OpenIdConnect").Bind(opts);
                opts.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                opts.CorrelationCookie = new Microsoft.AspNetCore.Http.CookieBuilder
                {
                    HttpOnly = false,
                    SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None,
                    SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.None,
                    Expiration = TimeSpan.FromMinutes(10)
                };

                opts.Events = new OpenIdConnectEvents()
                {
                    OnRedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    OnRemoteFailure = OnRemoteFailure,
                    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived
                };
                //opts.Events = new OpenIdConnectEvents
                //{
                //    OnAuthorizationCodeReceived = ctx =>
                //    {
                //        return Task.CompletedTask;
                //    }
                //};
            });

            //services.ConfigureApplicationCookie(options =>
            //{
            //    // Cookie settings
            //    options.Cookie.HttpOnly = true;
            //    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            //    options.SlidingExpiration = true;
            //});
        }

        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRemoteFailure(RemoteFailureContext arg)
        {
            return Task.FromResult(0);
        }

        private Task OnRedirectToIdentityProvider(RedirectContext arg)
        {
            return Task.FromResult(0);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

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

My appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },

  "ConnectionStrings": {
    "IdentityServerDb": "Server=localhost;Database=IdentityServer;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

  "OpenIdConnect": {
    "ClientId": "xxxxx",
    "Authority": "https://login.microsoftonline.com/xxxxx/",
    "PostLogoutRedirectUri": "/Account/SignoutOidc",
    "CallbackPath": "/Account/SigninOidc",
    "UseTokenLifetime": true,
    "RequireHttpsMetadata": false,
    //"ResponseType": "code id_token",
    "ClientSecret": "xxx",
    "Resource": "https://graph.microsoft.com/"
  }
}

And the implementation:

[HttpGet]
public IActionResult CorpLogin()
{
  var authProperties = _signInManager
                .ConfigureExternalAuthenticationProperties("AzureAD",
     Url.Action("SigninOidc", "Account", null, Request.Scheme));

   return Challenge(authProperties, "AzureAD");
}

[HttpPost]
public IActionResult SigninOidc([FromForm]object data)
{
//this never runs
   return Ok();
}
Wayne Yang
  • 9,016
  • 2
  • 20
  • 40
Augusto Sanchez
  • 999
  • 1
  • 6
  • 14
  • Um... Is there some proxy or firewall on your machine? – Wayne Yang May 11 '18 at 05:54
  • Maybe, but I could fixed the problem excluding asp.net identiy, do you know if there is any known issue at that? – Augusto Sanchez May 11 '18 at 16:04
  • 11
    The error description is very unhelpful to people unfamiliar with OIDC internals: I want to know exactly what "correlation failed" means - what X is trying to correlate what Y with what Z? – Dai Nov 28 '18 at 03:14
  • @Wayne in my case there is a proxy, any hint how to make that work even with proxy in place? – Samuel May 26 '19 at 01:54
  • The problem I had was that `RemoteAuthenticationTimeout` was set to just 30 seconds. When external authentication occasionally took longer you would get a correlation error. I extended it to the default of 15 minutes. – Wouter Sep 02 '22 at 12:00

21 Answers21

75

If you're using Chrome against localhost, you may have run into a change in Chrome cookie-handling behaviour.

To verify, navigate to chrome://flags/ and change "Cookies without SameSite must be secure" to "Disabled".

If that change fixes the issue, and you want to fix it permanently (i.e. not rely on the chrome flags fix), this thinktecture post talks about the underlying issue and some fixes that you'll need for old iOS safari versions.

dbruning
  • 5,042
  • 5
  • 34
  • 35
37

I was hitting this issue when using login with Google using .net Identity in Blazor on chrome. I had a new requirement to get it to work without https, it had been working fine with https.

I read in multiple answers variants of changing to

app.UseCookiePolicy(new CookiePolicyOptions()
{
    MinimumSameSitePolicy = SameSiteMode.None
});

I wish I'd read @dbruning's answer's article sooner. It mentioned in the article which isn't mentioned anywhere else: Please note: The setting SameSite=None will only work if the cookie is also marked as Secure and requires a HTTPS connection. The method's intellisense summary doesn't mention this which I think it definitely should...

So after that I just tried using SameSiteMode.Lax instead and it worked for me again. No other changes required from the default blazor project startup.cs

app.UseCookiePolicy(new CookiePolicyOptions()
{
    MinimumSameSitePolicy = SameSiteMode.Lax
});
James
  • 4,146
  • 1
  • 20
  • 35
  • 2
    This fixed it for me. Because I'm not exposing my identity server (keycloak) to the outside world, I don't want to set up HTTPS for nothing. Thanks @James! – Timo Hermans Nov 23 '20 at 19:14
  • Where exactly in your middleware pipeline did you put this? I'm asking since the order of middleware registration is important. – Pieterjan Jul 21 '21 at 12:54
  • My configure method looks like this: app.UseHsts(); app.UseStaticFiles(); app.UseRouting(); app.UseCookiePolicy(new CookiePolicyOptions() { MinimumSameSitePolicy = SameSiteMode.Lax }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(....) – James Jul 21 '21 at 16:48
  • not quite the answer I needed, but got me to realize that I wasn't using HTTPS – Angelo Bernardi Dec 13 '21 at 00:52
  • This worked for me in Configure(), but not at first because I originally had this option set up in ConfigureServices like services.Configure(options => { options.MinimumSameSitePolicy = SameSiteMode.None; }); which was not working when testing dev with localhost. – mfsumption Mar 17 '22 at 04:42
26

I was having a very similar issue and none of the answers posted in this whole thread worked for me. I will describe how I reached the solution, in case it can help anybody else.

In my case, I have a web app with ASP.NET Core 3.1 (migrated from 1.x) and implemented authentication with the following snippet in the ConfigureServices method, from Startup.cs (as described here):

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

The error thrown, as can be seen here, had a much simpler stack trace that the one described on this thread.

In the end, the problem was that cookies were not being set as secure. To do so, I just added the following code snippet right before the services.AddAuthentication pasted above.

services.Configure<CookiePolicyOptions>(options =>
{
    options.Secure = CookieSecurePolicy.Always;
});

Furthermore, I added a call to app.UseCookiePolicy() right before the call to app.UseRouting() in the Configure() method in Startup.cs.

tteguayco
  • 766
  • 1
  • 6
  • 16
  • 3
    This! This answer right here! I spent couple hours trying to fix this Correlation failed problem and nothing worked. But this solution, with pretty nice and straightforward step-by-step guide solved it for me. Thank you! – Bukk94 Jan 11 '22 at 19:22
  • 1
    SWEET JESUS, HALELUJAH! You should get a Nobel prize for world peace. – Ondrej Valenta Sep 19 '22 at 01:42
20

I've finally found the solution, I´ll post here just in case somebody have a similar problem.

Looks like the principal problem was that my redirect URI was the same that the CallBackPath:

"CallbackPath": "/Account/SigninOidc"

var authProperties = _signInManager .ConfigureExternalAuthenticationProperties("AzureAD", Url.Action("SigninOidc", "Account", null, Request.Scheme));

Well, here is my corrected Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BPT.PC.IdentityServer.Data;
using BPT.PC.IdentityServer.IdentityStore;
using BPT.PC.IdentityServer.Models;
using BPT.PC.IdentityServer.Web.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace BPT.PC.IdentityServer.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity<User, Role>()
                .AddUserStore<UserStore>()
                .AddRoleStore<RoleStore>()
                .AddDefaultTokenProviders();

            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddDbContext<IdentityServerDb>
                (options => options.UseSqlServer(Configuration.GetConnectionString("IdentityServerDb")));

            services
                .AddMvc();
            services
                .AddAuthentication(auth =>
                {
                    auth.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    auth.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    auth.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie()
                .AddOpenIdConnect("AzureAD", "AzureAD", options =>
                {
                    Configuration.GetSection("AzureAD").Bind(options); ;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(120);
                    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.RequireHttpsMetadata = false;
                    options.SaveTokens = true;
                });

            services.AddSingleton(Configuration.GetSection("OpenIdConnectProviderConfiguration").Get<OpenIdConnectProviderConfiguration>());

        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseAuthentication();

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

And the finally implementation:

[HttpGet]
public IActionResult CorpLogin()
    {
        var authProperties = _signInManager
            .ConfigureExternalAuthenticationProperties("AzureAD",
            Url.Action("LoggingIn", "Account", null, Request.Scheme));

        return Challenge(authProperties, "AzureAD");
    }

The appsettings.json is the same.

Augusto Sanchez
  • 999
  • 1
  • 6
  • 14
7

Just FYI: I met same issue which cost me almost 1 day to investigate on this issue. finally I found that after remove below code from my startup.cs and everything is working: CookiePolicyOptions cookiePolicy = new CookiePolicyOptions() { Secure = CookieSecurePolicy.Always, };

I am following up this with Microsoft support team, will update this back if get got any response.

Tim.Tang
  • 3,158
  • 1
  • 15
  • 18
6

The problem for me was that the clock on my machine (I am using a virtual machine) was not set to the correct time. It was behind by a few days because I had paused the VM after last using it.

So the solution was to simply adjust the clock to be the correct time.

rayray
  • 1,625
  • 1
  • 9
  • 15
4

This Happens when you try to access the URL which is assigned as 'Callback Path' in your OIDC settings.

To resolve this change your Callback Path to something like, 'MyController/MyAction' which will redirect you to your specific URL , in your case '/Account/SigninOidc'.

4

In my case, I had to go to Visual Studio menus,

Project=> Application Properties => Debug tab = Enable SSL true

And in the actual OAuth configuration in FB Developer's account, set use https. This has resolved. There may be different complicated problems for others. In my case this has sorted it.

Riyaz Hameed
  • 1,087
  • 12
  • 10
3

Thanks to Tim.Tang's answer, I figured out what caused the error on my end on Core 2.2. It was similar except that the error appeared when I removed the code for cookie policy in Startup.cs > ConfigureServices method:

services.Configure<CookiePolicyOptions>(options =>
{
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});

This was because I forgot to also remove app.UseCookiePolicy(); code in the Configure method.

Lukas
  • 1,699
  • 1
  • 16
  • 49
3

using this at top of my Configure method Solved My Issue

app.UseCookiePolicy(new CookiePolicyOptions()
    {
        MinimumSameSitePolicy = SameSiteMode.Lax
    });
1

Put this at the top of Startup.Configure(), before other middleware Uses:

app.UseCookiePolicy(new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Strict
});

Tested using IdentityServer 4.1.2, .NET Core 5

Michael Ribbons
  • 1,753
  • 1
  • 16
  • 26
1

For my case, I am getting this error when hosting the webapp inside Kubernetes with Nginx-Ingress as reverse proxy.

I noticed that the cookie is being stored in the browser, but with an incorrect path. The path is "/signin-oidc", instead of "/X/Y/signin-oidc", that's why the browser did not send the cookie to the webapp server when navigating to "/X/Y/signin-oidc".

The fix for me was to set the Cookie Path of the NonceCookie and CorrelationCookie to "/X/Y/signin-oidc"

builder.AddOpenIdConnect("oidc", options =>
{
    ...
    options.NonceCookie.Path = "/X/Y/signin-oidc";
    options.CorrelationCookie.Path = "/X/Y/signin-oidc";
});

Update: In the end, I did not set the NonceCookie or CorrelationCookie Path anymore. There are other corner cases not covered by this workaround. Instead, I simply set the pathbase value.

string pathBase = "/x/y";
app.UsePathBase(pathBase);
app.Use(async (context, next) =>
{
    context.Request.PathBase = pathBase;
    await next();
});
remondo
  • 318
  • 2
  • 7
0

This issue is mostly happening when you are running identity server on http and browser is chrome , try running the application on IE Edge or use https always should fix the issue

0

I had the exact same problem

Exception: Correlation failed.

while trying to authenticate my dotNet Core 3 app to AzureAD.

Changing my launch profile to "Project" and adding a https App URL ("https://localhost:5001;http://localhost:5000") actually did the trick for me!

0

In my case I had to provide a random sslPort in the launchSettings.json file, before it was 0.

"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
  "applicationUrl": "http://localhost:17950",
  "sslPort": 44312
}
Varun Sharma
  • 2,591
  • 8
  • 45
  • 63
0

I suddenly got this in every browser today while debugging in Visual Studio and fixed it by switching to IIS Express from Kestrel.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 19 '22 at 08:56
  • When hosting using Kestrel, are you under some reverse proxy (e.g. hosting it under "https://A:8000/B/C")? Maybe the context.Request.PathBase is not correct. Hosting under IIS automatically sets the Request.PathBase. But if running under Kestrel, it may not be automatically set. – remondo Jul 14 '22 at 02:31
0

I hit this and the issue turned out to be case sensitive cookie paths. I was lowercasing the redirect_uri (because these are case sensitive). And I think the middleware sets the cookie path based on "basePath".

My startup ended up looking like this:

services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
    {
            microsoftOptions.ClientId = configuration["Authentication:Microsoft:ClientId"];
            microsoftOptions.ClientSecret = configuration["Authentication:Microsoft:ClientSecret"];
            // The path is case sensitive so just override
            microsoftOptions.CorrelationCookie.Path = "/"; 
            microsoftOptions.Events.OnRedirectToAuthorizationEndpoint = context =>
            {
                var redirectUriParam = "redirect_uri";

                var uri = new UriBuilder(context.RedirectUri);
                var qs = HttpUtility.ParseQueryString(uri.Query);

                string returnUrl = qs.Get(redirectUriParam);
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    // The return urls are case sensitive so force this to lower case
                    qs.Set(redirectUriParam, returnUrl.ToLower());
                }

                uri.Query = qs.ToString();
                string redirectUrl = uri.Uri.ToString();
                context.Response.Redirect(redirectUrl);
                return Task.CompletedTask;
            };
        });

See also: https://github.com/IdentityServer/IdentityServer3/issues/1876

tappetyclick
  • 472
  • 2
  • 14
0

IF you are using Azure AD B2C, and see this error message:

Error.
An error occurred while processing your request.
Request ID: 00-0480476dfa246c5453a194d2c2964922-ee229bd333b36f8b-00

Details Correlation failed.

It means that you have not added the CallBack URL to the configuration.

To fix, log onto Azure, and switch to the Directory which has the Azure B2C.

Go to "App Registrations" and then select your App.

Then select "Authentication" on the left under "Manage".

It will then show you a list of "Redirect URIs".

Add the URL you were trying to use to this list.

After adding to the list wait an hour before testing as it takes Azure time to propagate this setting. If you test too soon, it will show the same error message.

enter image description here

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
0

I am using .net 7 MVC, with AWS Cognito setup as an OpenId provider.

I got this error when deploying the website on AWS App Runner. Worked fine locally.

The trick was adding the following code to Program.cs:

app.UseCookiePolicy(new CookiePolicyOptions
{
    Secure = CookieSecurePolicy.Always
});
Kappacake
  • 1,826
  • 19
  • 38
0

I had this issue in one of the projects and the below code fixed the issue for .net Core

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedProto
});
Kiran B
  • 683
  • 10
  • 21
-1

Having app on .NET 6. The app is on HTTP, because the HTTPS is provided by a load-balancer. I have problems with OAuth for Seznam Oauth provider (OAuth provider/e-mail service in the Czech Republic).

For me, the code that solve the problem was:

options.CorrelationCookie.SameSite = SameSiteMode.Lax;

In Startup.cs ConfigureServices method:

services.AddOAuth<CustomOAuthAuthenticationOptions, CustomOAuthClientAuthentication>("MyAuthScheme", "MyAuthScheme", options =>
{
    options.CorrelationCookie.SameSite = SameSiteMode.Lax;
});

Setting the CorrelationCookie help to solve the problem. Maybe it will work for other providers.

The reason I can't use the UseCookiePolicy extension method is that we support different authentication methods in our app, that requires different cookie options.

t00thy
  • 501
  • 5
  • 16