如何在身份验证/授权期间在 asp.net core 中设置 cookie

时间:2021-05-13 15:26:36

标签: c# asp.net-core cookies openid-connect

我试图在 cookie 和 openIdConnect 身份验证/授权期间设置自定义 cookie,但没有任何成功。我希望有人能指出我正确的方向。这是我的中间件设置:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie(option => {

            option.Events = new CookieAuthenticationEvents {
                 //Tried the OnSignedIn() to set the custom cookie but no avail
            }
                
        })
        .AddOpenIdConnect("Is4", options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.Authority = "identityserver4.url";
            options.RequireHttpsMetadata = false;
            options.ClientId = "ClientId";
            options.ClientSecret = "ClientSecret";
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.UsePkce = true;
            options.ResponseMode = "form_post";
            options.CallbackPath = "/signin-oidc";
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("offline_access");
            options.Scope.Add("customer-api"); 
           
            options.SaveTokens = true; 

            options.Events = new OpenIdConnectEvents
            {
                OnUserInformationReceived = (context) =>
                {
                    var accessTokenSplit = context.ProtocolMessage.AccessToken.Split(".");

                    context.Response.Cookies.Append(
                            key: "HeaderPayload",
                            value: $"{accessTokenSplit[0]}.{accessTokenSplit[1]}",
                            options: new CookieOptions
                            {
                                Domain = "localhost:5001",
                                SameSite = SameSiteMode.Strict,
                                Expires = DateTimeOffset.UtcNow.AddMinutes(30),
                                Secure = true,
                                HttpOnly = false
                            }
                        );

                    context.Response.Cookies.Append(
                            key: "Signature",
                            value: $"{accessTokenSplit[2]}",
                            options: new CookieOptions
                            {
                                Domain = "localhost:5001",
                                SameSite = SameSiteMode.Strict,
                                Expires = DateTimeOffset.UtcNow.AddMinutes(30),
                                Secure = true,
                                HttpOnly = true
                            }
                        );

                    return Task.CompletedTask;
                }
        });

HeaderPayloadSignature 是我希望浏览器在身份验证工作流程结束时拥有的自定义 cookie。相反,我只看到 .AspnetCore.CookiesC1 和 .AspnetCore.CookiesC2。我猜 cookie 身份验证中间件不知道我在 AddCookie() 或 AddopenIdConnect() 事件之一中设置的自定义 cookie。但是,我可以使用 context.Response.Cookies.Append(...) 在自定义中间件中设置这些 cookie 以显示在浏览器中,但我无法访问那里的 JWT 访问令牌,因此宁愿在身份验证管道中处理它。有什么想法或建议吗?谢谢

1 个答案:

答案 0 :(得分:0)

我发现了这个问题,它与 Cookie 或 OpenIdConnect 中间件无关。 x.replace(/<[^>]*>?/gm, ''); cookie 选项阻止浏览器创建 cookie。

我正在使用 VueJs asp.net 核心 SPA 模板。 Asp.net 核心将 SPA 的所有调用代理到 ​​Vuejs webpack 开发服务器。开发服务器在 IEnumerator coroutine() { float limit = 3; float elapsed = 0; while(elapsed < limit) { if(!IsPlayerStill()) { yield break; } elapsed += Time.deltaTime; yield return null; } method(); } 上托管 SPA,这不是安全连接,但我将 cookie 配置为仅用于 https (Secure=true)。因此,我在浏览器中没有看到 cookie。

现在我正在尝试将 webpack 服务器配置为使用自签名证书,这样 asp.net core 就不会抱怨由于证书验证失败而无法设置 ssl 连接。