如何解决IdentityServer4使用chrome 80版本进行登录后无法跳转的问题

     最近学习identityserver4时发现一个问题,使用chrome最新80的版本在登录后始终跳回到登录页面,用IE浏览器试了正常,经过网上搜索后发现原来是由于:

HTTP:浏览器的 SameSite 更改会影响身份验证

某些浏览器(如 Chrome 和 Firefox)对 Cookie 的 SameSite 实现进行了中断性变更。 这些变更会影响 OpenID Connect 和 WS 联合身份验证等远程身份验证方案,必须通过发送 SameSite=None 来选择退出。 但是,SameSite=None 会在 iOS 12 和其他浏览器的某些较早版本上中断运行。 应用需探查这些版本,并忽略 SameSite

https://docs.microsoft.com/zh-cn/dotnet/core/compatibility/3.0-3.1#http-browser-samesite-changes-impact-authentication

https://github.com/dotnet/aspnetcore/issues/14996

 

在下面找到了比较好的解决办法

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

为了支持Chrome 80版本,在上述方案基础上做如下修改:

添加类SameSiteCookiesServiceCollectionExtensions,代码如下

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();
                    options.SameSite = ReplaceSameSiteNoneByUserAgent(userAgent);
                 }
            }

            /// <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 SameSiteMode ReplaceSameSiteNoneByUserAgent(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 Unspecified;
                }

                // 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 Unspecified;
                }


            var ma = new Regex("Chrome/([0-9]+)").Match(userAgent);
            if (ma.Success && int.TryParse(ma.Groups[1].Value, out int chromeVer))
            {
                // 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 (chromeVer >= 50 && chromeVer <= 69)
                {
                    return Unspecified;
                }
                else if (chromeVer >= 80)
                {
                    return SameSiteMode.Lax;
                }
            }

               return SameSiteMode.None;
            }
        }
}

 在StartUp的ConfigureServices和Configure函数里添加如下代码

public void ConfigureServices(IServiceCollection services)
{
     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();
}

 

问题解决!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值