简体   繁体   中英

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. 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. Instead I only see.AspnetCore.CookiesC1 and.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. 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. Any thoughts or suggestions? Thanks

I found the problem and it has nothing to do with the Cookie or OpenIdConnect middleware. The Secure=true cookie option was preventing the browser from creating the cookie.

I'm using the VueJs asp.net core SPA template. Asp.net core is proxying all the calls for SPA to the Vuejs webpack dev server. 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 ). Therefore, I didn't see the cookie in the browser.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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