'Net CORE Keycloak and OIDC

I tried to create .Net Core 3.1 Web API which used Keycloak authorization. I want to implement the following scenario:

Browser sends some request to API.

  1. If user isn't authenticated, API redirects to Keycloak login page.
    API checks auth.
    API sends response.
    But it doesn't work

Into step 2 I have:

System.Exception: Correlation failed. at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.



Solution 1:[1]

if you are running your application on multiple instances behind a load-balancer, then you need to be sure that the same service instance is used through the entire authentication cycle. Otherwise you might the correlation error.

Solution 2:[2]

Not sure what your error is about as there was no configuration provided, but if you need to easily add KeyCloak authentication for your .Net Core backend you can use the following code (from package Delobytes.AspNetCore.Infrastructure)

services.AddKeyCloakAuthentication("SchemeName", true, options =>
    {
        options.Authority = "https://mykeycloakinstallation.com/auth/realms/myrealm"; //"issuer" endpoint
        options.Audience = "account";
        options.OpenIdConfigurationEndpoint = "https://mykeycloakinstallation.com/auth/realms/myrealm/.well-known/openid-configuration";
        options.TokenValidationParameters = new TokenValidationOptions
        {
            RequireExpirationTime = true,
            RequireSignedTokens = true,
            ValidateIssuer = true,
            ValidIssuer = "https://mykeycloakinstallation.com/auth/realms/myrealm",
            ValidateAudience = true,
            ValidAudience = "account",
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(2),
        };
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tore Nestenius
Solution 2 ??????? ??????