whyfate.github.io

1. 背景

一个asp.net core应用,采用了混合模式接入IdentityServer4,大致代码如下:

services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "http://localhost:5000"; //指定授权服务器的地址
        options.RequireHttpsMetadata = false; //不需要https
        options.ClientId = "mvc"; //指定客户端ID
        options.ClientSecret = "secret"; //指定客户端秘钥
        options.ResponseType = "code id_token"; //指定响应类型为混合模式
        options.SaveTokens = true; //保存访问令牌和刷新令牌
        options.GetClaimsFromUserInfoEndpoint = true; //从用户信息端点获取声明
        options.Scope.Add("api1"); //添加访问范围
        options.Scope.Add("offline_access"); //添加离线访问范围
    });

2. 问题

在应用升级到.net8后,在identityserver4登录成功后跳转回应用的时候报错;

info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12]
      AuthenticationScheme: OpenIdConnect was challenged.
warn: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15]
      '.AspNetCore.Correlation.jYHghatkRZxADBgSdV3xxbycWBMMTZEEvtNAlaHyleY' cookie not found.
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[4]
      Error from RemoteAuthentication: Correlation failed..
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      Microsoft.AspNetCore.Authentication.AuthenticationFailureException: An error was encountered while handling the remote login.

这个错误已经不是第一次出现;第一次出现这个错误还是在chrome 86版本修改cookie的SameSite默认值,之前使用SameSite=Unspecified解决了这个问题;

options.SameSite = SameSiteMode.Unspecified;

没想到升级.net8又出现了,当时还以为.net7也有这个问题,只是没发现,回退到.net7确实又没报错了,没办法只能通过对比两个版本的CookieOptions的值,期待有所收获,万万没想到真的是CookieOptions的Secure的默认值从false改成了true造成的,所以解决问题的代码变成了如下代码:

options.SameSite = SameSiteMode.Unspecified;
options.Secure = false;

第一次遇到SameSite的问题,就简单的看了一下关于SameSite值域的一些解释,并没有将Cookie的其他属性一起看一下,这次借着这个机会重新学习一下其他的Cookie的属性。

Http Cookie 教程
在 ASP.NET Core 中使用 SameSite cookie