2

I am using Sitecore 10.1.2 and we have integrated Key Cloak on the CM server, also we have disabled the Sitecore Identity server.

Below is the code:

     protected override void ProcessCore(IdentityProvidersArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            IdentityProvider = this.GetIdentityProvider();
            var httphandler = new HttpClientHandler();
            httphandler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
            //httphandler.SslProtocols = SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
            httphandler.CheckCertificateRevocationList = true;
            httphandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>
            {
                return true;
            };
            var httpclient = new HttpClient();
            httpclient.DefaultRequestHeaders.TryAddWithoutValidation(Settings.GetSetting(KeycloakSettings.HeaderKey1, ""), Settings.GetSetting(KeycloakSettings.HeaderValue1, ""));
            httpclient.DefaultRequestHeaders.TryAddWithoutValidation(Settings.GetSetting(KeycloakSettings.HeaderKey2, ""), Settings.GetSetting(KeycloakSettings.HeaderValue2, ""));
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            Log.Info("code entered ProcessCore", this);
 
            var options = new OpenIdConnectAuthenticationOptions
            {
                BackchannelHttpHandler = httphandler,
                //Backchannel = httpclient,
                RequireHttpsMetadata = false,
                MetadataAddress = MetadataAddress,
                ClientId = ClientId,
                ClientSecret = ClientSecret,
                Authority = Authority,
                RedirectUri = GetCallbackUrl(args),
                ResponseType = OpenIdConnectResponseType.Code,
                Scope = OpenIdScope,
                AuthenticationType = IdentityProvider.Name,
                RedeemCode = true,
                
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },
 
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = (AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification) =>
                    {
                        Log.Info("code entered the authentication failed event", this);
                        if (notification.Exception != null)
                        {
                            Log.Info($"Keycloak authorization fail with exception.\n {notification.Exception.Message}", this);
 
                            notification.HandleResponse();
 
                            // This exception should no longer be valid if we use inject KentorOwinCookieSaver middleware before OpenIdConnectAuthentication. However, we keep this code to safeguard against future.
                            if (notification.Exception.Message.Contains("IDX21323"))
                            {
                                notification.HandleResponse();
                                /* This line of code is the key to solve error 
                               IDX21323: RequireNonce is '[PII is hidden]'. OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null. 
                               The nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'. Note if a 'nonce' is found it will be evaluated.
                               */
                                notification.OwinContext.Authentication.Challenge();
                                return System.Threading.Tasks.Task.CompletedTask;
                            }
                        }
 
                        notification.HandleResponse();
                        notification.Response.Redirect(accessDeniedRelativePath);
 
                        return System.Threading.Tasks.Task.CompletedTask;
                    },
                    SecurityTokenValidated = OnSecurityTokenValidated,
                    //AuthorizationCodeReceived = ProcessAuthorizationCodeReceived,
                    RedirectToIdentityProvider = notification =>
                    {
                        Log.Info("code entered the RedirectToIdentityProvider event", this);
                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            notification.ProtocolMessage.SetParameter("kc_idp_hint", "saml");
                        }
                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
                        {
                            // If signing out, add the id_token_hint
                            var idTokenClaim = notification.OwinContext.Authentication.User.FindFirst(idToken);
 
                            if (idTokenClaim != null)
                                notification.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
                        }
 
                        return System.Threading.Tasks.Task.CompletedTask;
                    }
                }
            };
 
            // Sequence of this middleware matters. The KentorOwinCookieSave must comes before OpenIdConnectAuthentication.
            args.App.UseKentorOwinCookieSaver();
            args.App.UseOpenIdConnectAuthentication(options);
        }

Once I logged in through KeyCloak it works, but when I try to open the Sitecore login page in another tab in the same browser and again click on KeyCloak to login, it shows a Bad Request error:

The size of a request header field exceeds the server limit) error: enter image description here

When I log in for the first time I can see the below two cookies have been created:

  1. AspNet.CookiesC1 (Cookie size is 4047 Bytes)
  2. AspNet.CookiesC2 (Cookie size is 281 Bytes)

and when I do log in for the second time, two new cookies have been created:

  1. AspNet.ExternalCookies.C1 (Cookie size is 4047 Bytes)
  2. AspNet.ExternalCookies.C2 (Cookie size is 401 Bytes)

Any recommendations on how I can resolve the above error?

2 Answers 2

1

To solve this weird issue, I performed below two steps:

  1. When a user is already logged in and tries to open the login page in another tab then this issue was coming so to solve this issue, on RedirectToIdentityProvider method I checked if a user is already logged in then redirect to the dashboard page instead to go to Keycloak again.
 RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            if (Sitecore.Context.User.IsAuthenticated)
                            {
                                notification.HandleResponse();
                                notification.Response.Redirect(REDIRECTURL);
                            }
                            else
                            {                               
                        
      notification.ProtocolMessage.SetParameter("kc_idp_hint", "saml");
                            }
                        }
                        
                        return System.Threading.Tasks.Task.CompletedTask;
                    }
  1. Second scenario is that after session timeout when the user redirects to the login page then the user tries to log in again the same error was coming so to solve that I wrote a pipeline on httpRequestBegin
 public override void Process(HttpRequestArgs args)
        {
            if (Context.User.IsAuthenticated || Context.User?.Name == null || !Context.PageMode.IsNormal)
            {
                return;
            }
            CacheManager.ClearSecurityCache(Context.User.Name);
            RecentDocuments.Remove(Context.User.Name);
            Sitecore.Shell.Framework.Security.Abandon();
            string currentTicketId = TicketManager.GetCurrentTicketId();
            if (string.IsNullOrEmpty(currentTicketId))
            {
                return;
            }
            TicketManager.RemoveTicket(currentTicketId);
        }
0

Your error is clear: the server does have some issues with a requestheader field which is to large. This can be any header, but keep in mind that a set of cookies is a header as well.

as the request gives an error, this has to happen on your load balancer, reverse proxy, firewall, or webserver. Depending on the technology behind it, the allowed size can vary:

Apache 8K Nginx 4K-8K IIS 8K-16K Tomcat 8K – 48K

(source: )

Start with checking your IIS settings header limits and work towards your entrypoint to find the place where the setting is to narrow.

1
  • Thanks, Bas Lijten. IIS already has max header size May 24, 2023 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.