简体   繁体   English

继续使用 OIDC JS 客户端和身份服务器获取 session 4 在 Azure 应用程序服务上使用 PKCE 流的授权流

[英]Keep getting session out with OIDC JS client and Identity server 4 Authorization flow with PKCE flow on Azure app services

Using Identity server 4 with OIDC JS client in every 10 seconds the application reloads, in the network tabs I can see在应用程序每 10 秒重新加载一次时,将 Identity server 4 与 OIDC JS 客户端一起使用,在我可以看到的网络选项卡中

在此处输入图像描述

The end session URL is always been canceled and application reload frequently结尾 session URL 总是被取消,应用重载频繁

Request URL: https://falconidentityserver.azurewebsites.net/connect/endsession?id_token_hint=eyJhbGciOiJSUzI1NiIsImtpZCI6IjU1RDY5MTZFODVCOUNENTgwRjQ0RTMzNzREMjZFOUFCIiwidHlwIjoiSldUIn0.eyJuYmYiOjE2MTAzNzU0NjQsImV4cCI6MTYxMDM3NTc2NCwiaXNzIjoiaHR0cHM6Ly9mYWxjb25pZGVudGl0eXNlcnZlci5henVyZXdlYnNpdGVzLm5ldCIsImF1ZCI6IkZldGVfQmlyZF9VSSIsImlhdCI6MTYxMDM3NTQ2NCwiYXRfaGFzaCI6IlVDaUt3LXBBdi14aFVINFRZVXk1a1EiLCJzX2hhc2giOiI5clc3UUY5ZEtqRXdubE9lTWpRTTVBIiwic2lkIjoiQjYwNEJBNEU5MTEyOURCQjYzNTJFOEJDNDZFQUM5QkUiLCJzdWIiOiJlNDEzMTIwYS0yYWEzLTQzZTktYTQ1MC1lZWU2NzBjY2EzMjEiLCJhdXRoX3RpbWUiOjE2MTAzNzU0NTEsImlkcCI6ImxvY2FsIiwiYW1yIjpbInB3ZCJdfQ.lmfq1ZJ2ukkrZ-FPjtCPaEsBYM0HXCAF496dNGMH0WP-SBFbbSllLSPGcavpruzzA0n-JQmkshtEqhyMvk5-c81dQLgjblrQ-X5QrzGoRd6fXDMnWwR0dlm2ZC2TcPOcBJXdaW1nfjLChxxrQljHMNLBr1tAmPfTfx0kaG7uvoXg1iY1aNmBsFUs4erdYs24Wd0JPtGzlHrGc3wyXk7aJNS77Ocu9SHUTL5XLsecOPMX0CVqeAX0ibRT6b-VuJ6u0egMKzR6yS8vCx4DNdHIScuX-zyMvisDePiCwqbN_K9VE0iwy2CmNfMKmioPX-aora7V1qZwCdj2-Lp-OSVVwg

在此处输入图像描述

Identity server client setting身份服务器客户端设置

new Client
                {
                    ClientId = "XXXXXXXXXXXXXX",
                    ClientName = "XXXXXXXXXXXXXXXX",
                    AllowedCorsOrigins = CorsUris(configuration),
                    AllowedGrantTypes = GrantTypes.Code,
                    AllowAccessTokensViaBrowser = bool.Parse(configuration.GetSection("IdentityServer:Client:AllowAccessTokensViaBrowser").Value),
                    IdentityTokenLifetime = 300,
                    AccessTokenLifetime = 200,
                    RequireConsent = bool.Parse(configuration.GetSection("IdentityServer:Client:RequireConsent").Value),
                    UpdateAccessTokenClaimsOnRefresh = bool.Parse(configuration.GetSection("IdentityServer:Client:UpdateAccessTokenClaimsOnRefresh").Value),
                    RedirectUris = LocalRedirectUris(configuration),
                    PostLogoutRedirectUris = LocalRedirectUris(configuration),
                    AllowedScopes = AllowedScopes(),
                    AllowOfflineAccess = bool.Parse(configuration.GetSection("IdentityServer:Client:AllowOfflineAccess").Value),
                    AccessTokenType = AccessTokenType.Jwt,
                    RequireClientSecret = bool.Parse(configuration.GetSection("IdentityServer:Client:RequireClientSecret").Value),
                    RequirePkce = bool.Parse(configuration.GetSection("IdentityServer:Client:RequirePkce").Value),
                    //AllowRememberConsent = true
                },

OIDC client setting OIDC 客户端设置

openID = {
authority: 'https://falconidentityserver.azurewebsites.net',
client_id: 'xxxxxxxx',
redirect_uri: 'https://localhost:4200/auth-callback',
silent_redirect_uri: 'https://localhost:4200/assets/silent-renew.html',
response_type: 'code',
scope: 'openid profile email',
automaticSilentRenew: true

}; };

I don't know what I am missing and where is the issue.我不知道我错过了什么,问题出在哪里。 Can anyone help me with the this issue谁能帮我解决这个问题

I am doing silent reniew and it is working fine as you can see in the network tab.我正在做静默更新,它工作正常,正如您在网络选项卡中看到的那样。

OIDC usermanager logs OIDC 用户管理器日志

在此处输入图像描述

The issue for me was我的问题是

Single-signout (monitorSession: true) What does this do?单点注销 (monitorSession: true) 这是做什么的? -- After you login into your application (post redirect from IDP server, OIDC-Client JS will include the CheckSession endpoint in an iframe and OIDC library internally pings this iframe every 2 seconds (default) to verify that the idsrv.session cookie value matches with the value inside the applications id token, If they do not match, OIDC will raise user signed out event addUserSignedOut. It is up to your application, how you want to handle when this even get raised from OIDC. Just because you enable single sign out, unless application handles, it will not take the user back to login page -- After you login into your application (post redirect from IDP server, OIDC-Client JS will include the CheckSession endpoint in an iframe and OIDC library internally pings this iframe every 2 seconds (default) to verify that the idsrv.session cookie value matches使用应用程序 id 令牌中的值,如果它们不匹配,OIDC 将引发用户注销事件 addUserSignedOut。这取决于您的应用程序,当这甚至从 OIDC 引发时您想要如何处理。仅仅因为您启用了单点登录out,除非应用程序处理,否则不会将用户带回登录页面

After digging more from the below source从以下来源挖掘更多内容后

https://github.com/IdentityModel/oidc-client-js/issues/729 https://github.com/IdentityModel/oidc-client-js/issues/729

https://github.com/IdentityServer/IdentityServer4/issues/1983 https://github.com/IdentityServer/IdentityServer4/issues/1983

I need to add我需要添加

builder.Services.ConfigureApplicationCookie(options =>
            {
                // we need to disable to allow iframe for authorize requests
                options.Cookie.SameSite = SameSiteMode.None;
            });

Now the application working fine in CHROME but not in SAFARI .现在该应用程序在CHROME中运行良好,但在SAFARI中运行良好。

I need to manage Upcoming SameSite Cookie Changes in ASP.NET and ASP.NET Core我需要管理 ASP.NET 和 ASP.NET 核心中即将发生的 SameSite Cookie 更改

https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/ https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/

https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1#supporting-older-browsers https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1#supporting-older-browsers

https://www.identityserver.com/documentation/saml2p/config-sp/samesitecookies/ https://www.identityserver.com/documentation/saml2p/config-sp/samesitecookies/

https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/ https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/

Add the below class添加以下 class

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
 
namespace Microsoft.Extensions.DependencyInjection
{
   public static class SameSiteCookiesServiceCollectionExtensions
   {
      /// <summary>
      /// -1 defines the unspecified value, which tells ASPNET Core to NOT
      /// send the SameSite attribute. With ASPNET Core 3.1 the
      /// <seealso cref="SameSiteMode" /> enum will have a definition for
      /// Unspecified.
      /// </summary>
      private const SameSiteMode Unspecified = (SameSiteMode) (-1);
 
      /// <summary>
      /// Configures a cookie policy to properly set the SameSite attribute
      /// for Browsers that handle unknown values as Strict. Ensure that you
      /// add the <seealso cref="Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware" />
      /// into the pipeline before sending any cookies!
      /// </summary>
      /// <remarks>
      /// Minimum ASPNET Core Version required for this code:
      ///   - 2.1.14
      ///   - 2.2.8
      ///   - 3.0.1
      ///   - 3.1.0-preview1
      /// Starting with version 80 of Chrome (to be released in February 2020)
      /// cookies with NO SameSite attribute are treated as SameSite=Lax.
      /// In order to always get the cookies send they need to be set to
      /// SameSite=None. But since the current standard only defines Lax and
      /// Strict as valid values there are some browsers that treat invalid
      /// values as SameSite=Strict. We therefore need to check the browser
      /// and either send SameSite=None or prevent the sending of SameSite=None.
      /// Relevant links:
      /// - https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
      /// - https://tools.ietf.org/html/draft-west-cookie-incrementalism-00
      /// - https://www.chromium.org/updates/same-site
      /// - https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
      /// - https://bugs.webkit.org/show_bug.cgi?id=198181
      /// </remarks>
      /// <param name="services">The service collection to register <see cref="CookiePolicyOptions" /> into.</param>
      /// <returns>The modified <see cref="IServiceCollection" />.</returns>
      public static IServiceCollection ConfigureNonBreakingSameSiteCookies(this IServiceCollection services)
      {
         services.Configure<CookiePolicyOptions>(options =>
         {
            options.MinimumSameSitePolicy = Unspecified;
            options.OnAppendCookie = cookieContext =>
               CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            options.OnDeleteCookie = cookieContext =>
               CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
         });
 
         return services;
      }

      private static void CheckSameSite(HttpContext httpContext, CookieOptions options)
      {
         if (options.SameSite == SameSiteMode.None)
         {
            var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

            if (DisallowsSameSiteNone(userAgent))
            {
               options.SameSite = Unspecified;
            }
         }
      }
 
      /// <summary>
      /// Checks if the UserAgent is known to interpret an unknown value as Strict.
      /// For those the <see cref="CookieOptions.SameSite" /> property should be
      /// set to <see cref="Unspecified" />.
      /// </summary>
      /// <remarks>
      /// This code is taken from Microsoft:
      /// https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
      /// </remarks>
      /// <param name="userAgent">The user agent string to check.</param>
      /// <returns>Whether the specified user agent (browser) accepts SameSite=None or not.</returns>
      private static bool DisallowsSameSiteNone(string userAgent)
      {
         // Cover all iOS based browsers here. This includes:
         //   - Safari on iOS 12 for iPhone, iPod Touch, iPad
         //   - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
         //   - Chrome on iOS 12 for iPhone, iPod Touch, iPad
         // All of which are broken by SameSite=None, because they use the
         // iOS networking stack.
         // Notes from Thinktecture:
         // Regarding https://caniuse.com/#search=samesite iOS versions lower
         // than 12 are not supporting SameSite at all. Starting with version 13
         // unknown values are NOT treated as strict anymore. Therefore we only
         // need to check version 12.
         if (userAgent.Contains("CPU iPhone OS 12")
            || userAgent.Contains("iPad; CPU OS 12"))
         {
            return true;
         }

         // Cover Mac OS X based browsers that use the Mac OS networking stack.
         // This includes:
         //   - Safari on Mac OS X.
         // This does not include:
         //   - Chrome on Mac OS X
         // because they do not use the Mac OS networking stack.
         // Notes from Thinktecture: 
         // Regarding https://caniuse.com/#search=samesite MacOS X versions lower
         // than 10.14 are not supporting SameSite at all. Starting with version
         // 10.15 unknown values are NOT treated as strict anymore. Therefore we
         // only need to check version 10.14.
         if (userAgent.Contains("Safari")
            && userAgent.Contains("Macintosh; Intel Mac OS X 10_14")
            && userAgent.Contains("Version/"))
         {
            return true;
         }

         // Cover Chrome 50-69, because some versions are broken by SameSite=None
         // and none in this range require it.
         // Note: this covers some pre-Chromium Edge versions,
         // but pre-Chromium Edge does not require SameSite=None.
         // Notes from Thinktecture:
         // We can not validate this assumption, but we trust Microsofts
         // evaluation. And overall not sending a SameSite value equals to the same
         // behavior as SameSite=None for these old versions anyways.
         if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
         {
            return true;
         }

         return false;
      }
   }
}

Configure and enable cookies配置并启用 cookies

public void ConfigureServices(IServiceCollection services)
{
   // Add this
   services.ConfigureNonBreakingSameSiteCookies();
}
 
public void Configure(IApplicationBuilder app)
{
   // Add this before any other middleware that might write cookies
   app.UseCookiePolicy();

   // This will write cookies, so make sure it's after the cookie policy
   app.UseAuthentication();
}

After doing all the changes, still, I am facing issue in SAFARI完成所有更改后,我仍然面临SAFARI的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Identity Server 4 授权代码流示例 - Identity Server 4 Authorization Code Flow example 带有客户端机密的Identity Server 4混合流错误 - Identity Server 4 Hybrid Flow error with Client Secret 身份服务器:在 MVC 客户端的混合流中添加对访问令牌的声明 - Identity Server: Add claims to access token in hybrid flow in MVC client 受信任桌面客户端的客户端凭据流或授权代码流(使用 PCKE) - Client Credentials Flow or Authorization Code Flow (with PCKE) for a trusted desktop client 使用客户端凭据流进行Swashbuckle OAuth2授权 - Swashbuckle OAuth2 Authorization with Client Credentials Flow 带有 PKCE 帮助的授权流程.. 对于本机移动后端 restful api asp.net 核心 C# - Authorization Flow with PKCE help.. For Native mobile backend restful api asp.net core C# 处理Identity Server客户端凭据流时在自签名客户端证书中出现问题 - Issue in Self Signed Client Certificate while processing an Identity Server Client Credentials Flow 使用OAuth2客户端凭据流保护Azure API管理中的后端服务 - Securing Back end services in Azure API Management using OAuth2 Client Credentials flow Identity Server 4 隐式流 - 未知错误 - Identity Server 4 Implicit Flow - Unknown Error WebAPI2:微服务架构中的授权代码流程 - WebAPI2: Authorization code flow in micro services architecture
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM