身份服务器 4 登录后重定向仅在 Chrome 中不起作用

Pas*_*man 10 .net-core identityserver4

我使用身份服务器 4,称之为“身份验证服务器”,在 .net core 3.1 上运行。重定向到 auth-server 并提供提交登录的凭据后,有角度应用程序请求身份验证,它不会重定向回客户端应用程序。问题仅在 chrome 浏览器中(firefox 和 edge 工作正常)我可以看到重定向请求 - Request-Url 但它只是返回登录页面客户端配置:

public static IEnumerable<Client> GetClients()
{
    return new List<Client>(){
            new Client() {
                             RequireConsent =false,
                             RequireClientSecret = false,
                             ClientId = "takbull-clientapp-dev",
                             ClientName = "Takbull Client",
                             AllowedGrantTypes = GrantTypes.ImplicitAndClientCredentials,
                             AllowedScopes = new List<string> 
                             {
                              IdentityServerConstants.StandardScopes.OpenId,
                              IdentityServerConstants.StandardScopes.Email,
                              IdentityServerConstants.StandardScopes.Profile,
                              "takbull",
                              "takbull.api" 
                             },
                             // where to redirect to after login
                             RedirectUris = new List<string>()
                             {
                                 "http://localhost:4200/auth-callback/",
                                 "http://localhost:4200/silent-refresh.html",
                             },
                             //TODO: Add Production URL
                             // where to redirect to after logout
                             PostLogoutRedirectUris =new List<string>() 
                             {
                                 "http://localhost:4200"
                             },
                             AllowedCorsOrigins = {"http://localhost:4200"},
                             AllowAccessTokensViaBrowser = true,
                             AccessTokenLifetime = 3600,
                             AlwaysIncludeUserClaimsInIdToken = true
                         },
        };
    }
Run Code Online (Sandbox Code Playgroud)

登录代码:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
    // check if we are in the context of an authorization request
    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

    // the user clicked the "cancel" button
    if (button != "login")
    {
        if (context != null)
        {
            // if the user cancels, send a result back into IdentityServer as if they 
            // denied the consent (even if this client does not require consent).
            // this will send back an access denied OIDC error response to the client.
            await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

            // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
            if (await _clientStore.IsPkceClientAsync(context.ClientId))
            {
                // if the client is PKCE then we assume it's native, so this change in how to
                // return the response is for better UX for the end user.
                return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
             }

             return Redirect(model.ReturnUrl);
         }
         else
         {
            // since we don't have a valid context, then we just go back to the home page
            return Redirect("~/");
         }
     }

     if (ModelState.IsValid)
     {
         // validate username/password against in-memory store
         var ValidResp = await _users.ValidateCredentials(model.Username, model.Password);
         if (ValidResp.LogInStatus == LogInStatus.Success)
         {
             var user = _users.FindByUsername(model.Username);
             //await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username));
             await _events.RaiseAsync(new UserLoginSuccessEvent(user.Email, user.UserId.ToString(), user.Email));

             // only set explicit expiration here if user chooses "remember me". 
             // otherwise we rely upon expiration configured in cookie middleware.
             AuthenticationProperties props = null;
             if (AccountOptions.AllowRememberLogin && model.RememberLogin)
             {
                 props = new AuthenticationProperties
                 {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.Now.Add(AccountOptions.RememberMeLoginDuration)
                 };
             };

             // issue authentication cookie with subject ID and username
             //await HttpContext.SignInAsync(user.SubjectId, user.Username, props);
             // issue authentication cookie with subject ID and username
             await HttpContext.SignInAsync(user.UserId.ToString(), user.FirstName + " " + user.LastName, props, _users.GetClaims(user).ToArray());

             if (context != null)
             {
                 if (await _clientStore.IsPkceClientAsync(context.ClientId))
                 {
                     // if the client is PKCE then we assume it's native, so this change in how to
                     // return the response is for better UX for the end user.
                     return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
                 }

                 // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                 return Redirect(model.ReturnUrl);
             }

             // request for a local page
             if (Url.IsLocalUrl(model.ReturnUrl))
             {
                 return Redirect(model.ReturnUrl);
             }
             else if (string.IsNullOrEmpty(model.ReturnUrl))
             {
                 return Redirect("~/");
             }
             else
             {
                 // user might have clicked on a malicious link - should be logged
                 throw new Exception("invalid return URL");
             }
         }

         await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, ValidResp.ResponseDescription));
         ModelState.AddModelError(string.Empty, ValidResp.ResponseDescription);
     }

     // something went wrong, show form with error
     var vm = await BuildLoginViewModelAsync(model);
     return View(vm);
}
Run Code Online (Sandbox Code Playgroud)

ema*_*tez 9

我在 .NET Core 2.2 上遇到了 IdentityServer4 类似的问题。您的问题可能与 Chrome 或 Firefox 等新浏览器版本中的那些重大更改有关:

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

对我来说,可行的解决方案是完全关闭cookie的SameSite配置。此处描述了 .NET Core 2.2 的这种可能性:

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

(如果您的解决方案是在 .NET Core 3.1 上,那么在下面的代码中,而不是使用 (SameSiteMode)(-1)您应该使用SameSiteMode.Unspecified)

修复:在ConfigureServices方法的Startup.cs文件中,在创建IdentityServerBuilder之后...

var builder = services.AddIdentityServer(options =>
            {....});
Run Code Online (Sandbox Code Playgroud)

...我添加了以下配置更改:

builder.Services.ConfigureExternalCookie(options => {
   options.Cookie.IsEssential = true;
      options.Cookie.SameSite = (SameSiteMode)(-1); //SameSiteMode.Unspecified in .NET Core 3.1
   });

builder.Services.ConfigureApplicationCookie(options => {
   options.Cookie.IsEssential = true;
      options.Cookie.SameSite = (SameSiteMode)(-1); //SameSiteMode.Unspecified in .NET Core 3.1
});
Run Code Online (Sandbox Code Playgroud)


Bas*_*hir 9

我最近遇到了 chrome 和 edge 的问题,但几个月前只有 chrome。因此,对于 .Net Core 3 和 IdentityServer4 版本 3.1.2 的我来说,通过将以下代码添加到 startup.cs 开始工作:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ...)
    {
            app.UseCookiePolicy(new CookiePolicyOptions
            {
                MinimumSameSitePolicy = SameSiteMode.Lax
            });
Run Code Online (Sandbox Code Playgroud)

注意:确保将此策略添加到配置方法的开头,而不是在 startup.cs 中结束,否则将不起作用。


Anu*_*iti 5

您将在 Google Chrome 中遇到控制台冲突,并且您的身份服务器无法重定向到 Chrome 版本 80 的客户端应用程序。

与资源关联的 cookie 设置为 SameSite=None 但没有 Secure。它已被阻止,因为 Chrome 现在只提供标记为 SameSite=None 的 cookie,如果它们也标记为安全。您可以在应用程序>存储>Cookies 下的开发人员工具中查看 cookie,并在https://www.chromestatus.com/feature/5633521622188032 上查看更多详细信息。

要解决此问题,您需要在以下链接中进行更改 -

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

注意:对于 .Net Core 2.2,设置 SameSite = (SameSiteMode)(-1) ,对于 .Net Core 3.0 或更高版本,设置 SameSite = SameSiteMode.Unspecified

此外,对于 Chrome 80 版本,添加此额外条件 -

 if (userAgent.Contains("Chrome/8"))
 {
     return true;
 }
Run Code Online (Sandbox Code Playgroud)