Saml Состояние сохранения без файлов cookie ASP.NET CORE

Aug 20 2020
 var certbase = _env.IsDevelopment() ? "" : AppDomain.CurrentDomain.BaseDirectory;
 var pathpfx = Path.Combine(certbase, "xxxxx.pfx");
 var pathxml = Path.Combine(certbase, "metadata.xml");


.AddSaml2(options =>
                {  
                    options.SPOptions.EntityId = new EntityId("https://aaaa.aaa.com.tr");          
                    options.SPOptions.ReturnUrl = new Uri("https://localhost:5003/Account/SignInPost");
                    options.SPOptions.MinIncomingSigningAlgorithm = 
 "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
                    options.IdentityProviders.Add(
                    new IdentityProvider(
                    new EntityId("https://bbbbb.bbb.com.tr"), options.SPOptions)
                    {
                        MetadataLocation = pathxml,
                        LoadMetadata = true,
                        SingleSignOnServiceUrl = new Uri("https://bbbbb.bbb.com.tr/SAML/SSOService.aspx"),
                        Binding = Sustainsys.Saml2.WebSso.Saml2Binding.UriToSaml2BindingType(new 
 Uri("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")),
                        SingleLogoutServiceUrl = new Uri("https://bbbbb.bbb.com.tr/SAML/SLOService.aspx"),
                    });
                    options.SPOptions.ServiceCertificates.Add(new X509Certificate2(pathpfx, "password"));
                });

Мой saml работал правильно, но я не знаю, что случилось, мой код сейчас не работает.

Я получил эту ошибку, когда запустил свой код в Chrome =>

UnexpectedInResponseToException: полученное сообщение _55ae387d-0b1e-4466-9b2b-d34a5254437c содержит неожиданный InResponseTo «iddfcfd98961654500864ee897d823ce87». Состояние сохранения файлов cookie из запроса не обнаружено, поэтому не ожидалось, что сообщение будет иметь атрибут InResponseTo. Эта ошибка обычно возникает, если файл cookie, установленный при входе в систему по инициативе SP, был утерян.

Мой metadata.xml в порядке, мой pfx тоже в порядке.

Я искал решение своей проблемы более двух дней, но не нашел ничего, что могло бы мне помочь. Какое ваше предложение по решению этой проблемы? не могли бы вы помочь мне?

внутри стека

UnexpectedInResponseToException: Received message _63021ef9-2b93-4b0a-ab75-88d42e8a4c9c contains unexpected InResponseTo "idc0faf551a5bf421da3a9e582b57f685a". No cookie preserving state from the request was found so the message was not expected to have an InResponseTo attribute. This error typically occurs if the cookie set when doing SP-initiated sign on have been lost.



Sustainsys.Saml2.Saml2P.Saml2Response.ValidateInResponseTo(IOptions options, IEnumerable<ClaimsIdentity> claimsIdentities)
Sustainsys.Saml2.Saml2P.Saml2Response.GetClaims(IOptions options, IDictionary<string, string> relayData)
Sustainsys.Saml2.WebSso.AcsCommand.ProcessResponse(IOptions options, Saml2Response samlResponse, StoredRequestState storedRequestState, IdentityProvider identityProvider, string relayState)
Sustainsys.Saml2.WebSso.AcsCommand.Run(HttpRequestData request, IOptions options)
Sustainsys.Saml2.AspNetCore2.Saml2Handler.HandleRequestAsync()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Ответы

1 İbrahim Sep 02 2020 at 08:41

установите это в startup.cs

services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.OnAppendCookie = cookieContext => SameSite.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            options.OnDeleteCookie = cookieContext => SameSite.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);

            //this is important. this will help you to solve the problem.
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

и добавьте этот метод в public void configure () {}

 public static class SameSite
    {
        public static void CheckSameSite(HttpContext httpContext, CookieOptions options)
        {
            if (options.SameSite == SameSiteMode.None)
            {
                if (!BrowserSupportsSameSiteNone(httpContext.Request.Headers["User-Agent"].ToString()))
                {
                    // Unspecified - no SameSite will be included in the Set-Cookie.
                    options.SameSite = (SameSiteMode)(-1);
                }
            }
        }

        private static bool BrowserSupportsSameSiteNone(string userAgent)
        {
            // iOS 12 browsers don't support SameSite=None.
            if (userAgent.Contains("CPU iPhone OS 12") || userAgent.Contains("iPad; CPU OS 12"))
            {
                return false;
            }

            // macOS 10.14 Mojave browsers don't support SameSite=None.
            if (userAgent.Contains("Macintosh; Intel Mac OS X 10_14") && userAgent.Contains("Version/") && userAgent.Contains("Safari"))
            {
                return false;
            }

            // Old versions of Chrome don't support SameSite=None.
            if (userAgent.Contains("Chrome") || userAgent.Contains("Chrome/6"))
            {
                return false;
            }

            return true;
        }
    }