简体   繁体   English

如何在认证/授权期间在 asp.net 内核中设置 cookies

[英]How to set cookies in asp.net core during authenticaiton/authorization

I am trying to set custom cookies during the cookie and openIdConnect authentication/authorization in asp.net core 3.1 but not having any success.我正在尝试在 asp.net 核心 3.1 中的 cookie 和 openIdConnect 身份验证/授权期间设置自定义 cookies 但没有任何成功。 I hope someone can point me in the right direction.我希望有人能指出我正确的方向。 Here is my middleware setup:这是我的中间件设置:

        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;
                }
        });

The HeaderPayload and Signature are my custom cookies I want the browser to have at the end of the authentication workflow. HeaderPayloadSignature是我的自定义 cookies 我希望浏览器在身份验证工作流程结束时拥有。 Instead I only see.AspnetCore.CookiesC1 and.AspnetCore.CookiesC2.相反,我只看到.AspnetCore.CookiesC1 和.AspnetCore.CookiesC2。 I guess the cookie authentication middleware is not aware of my custom cookie I set in one of the AddCookie() or AddopenIdConnect() events.我猜 cookie 身份验证中间件不知道我在 AddCookie() 或 AddopenIdConnect() 事件之一中设置的自定义 cookie。 I can however set those cookies in a custom middleware with context.Response.Cookies.Append(...) to show up in the browser but I won't have access to the JWT access token there so would rather handle it in the authentication pipeline.但是,我可以将这些 cookies 设置在带有context.Response.Cookies.Append(...)的自定义中间件中以显示在浏览器中,但我无法访问 Z1D1FADBD9150349C135781140FFFEE9D,所以宁愿在身份验证中处理它管道。 Any thoughts or suggestions?有什么想法或建议吗? Thanks谢谢

I found the problem and it has nothing to do with the Cookie or OpenIdConnect middleware.我发现了问题,它与 Cookie 或 OpenIdConnect 中间件无关。 The Secure=true cookie option was preventing the browser from creating the cookie. Secure=true cookie 选项阻止浏览器创建 cookie。

I'm using the VueJs asp.net core SPA template.我正在使用 VueJs asp.net 核心 SPA 模板。 Asp.net core is proxying all the calls for SPA to the Vuejs webpack dev server. Asp.net 核心将所有对 SPA 的调用代理到 Vuejs webpack 开发服务器。 The dev server is hosting the SPA on http which is NOT a secure connection but I'm configuring the cookie to be used only with https ( Secure=true ).开发服务器在http上托管 SPA,这不是安全连接,但我将 cookie 配置为仅与 https ( Secure=true ) 一起使用。 Therefore, I didn't see the cookie in the browser.因此,我没有在浏览器中看到 cookie。

Now I'm trying to configure the webpack server to use a self-signed cert so asp.net core wouldn't complain that it can't setup the ssl connection because of the failing cert validation.现在我正在尝试将 webpack 服务器配置为使用自签名证书,因此 asp.net 核心不会抱怨它无法设置 ZF9D5C16A7F42203F8C195432354A3271 验证连接。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM