0

I'm trying to set Cookie HTTP Only to the client (Browser) using .NET Core and NextJS as front-end

The problem is when I made a request in postman the cookies are there Postman Token HTTP Only successful

So I don't need to send the token through the Authorization Bearer token, and I can made request to Apis which they need a valid token.

But I'm trying to handle in front-end but I can't set the Cookie Http only in browser Client(Browser Image)

as you can see the token is there but in Cookie Section the cookie is not available Browser Cookie Not Appear

this is the code in Startup

    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddCookie()
            .AddJwtBearer(options =>
            {
                options.Events = new  JwtBearerEvents(){
                       OnMessageReceived = context =>
                    {
                        var request = context.HttpContext.Request;
                        var cookies = request.Cookies;
                        if (cookies.TryGetValue("token", out var accessTokenValue))
                        {
                            context.Token = accessTokenValue;
                        }
                        Console.WriteLine(context.Token);
                        return Task.CompletedTask;
                    }
                };                  
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
                    ClockSkew = TimeSpan.Zero
                };
            });
 builder.Services.AddCors(options =>
    {
        options.AddPolicy("myCors", builder =>
        {
            builder.WithOrigins("http://localhost:3000");
            //builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
            builder.AllowAnyMethod();
            builder.AllowAnyHeader();
            builder.AllowCredentials();
        });

this is the configuration in method to Authenticate user and return token and setting a cookie

This is the request in Front-end

     const handleSubmit = async (e) => {
      e.preventDefault();
      try {
         const result = await fetch(URL + 'Auth/Login', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(formValues)});
         console.log(result.status);
         if (result.status === 200) {
            const data = await result.json();
            console.log(data);
         }
      } catch (e) {}
   };
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Siumauricio
  • 101
  • 1
  • 5
  • Does this answer your question? [Set cookies for cross origin requests](https://stackoverflow.com/questions/46288437/set-cookies-for-cross-origin-requests) – juliomalves Jan 21 '22 at 11:24

1 Answers1

0

AddJwtBearer never deals with cookies and adding .AddCookie() in this example does not make any sense.

For AddCookie() to issue an cookie, then someone needs to signing the user and AddJwtBearer never does that.

But it is a bit unclear what you actually tries to achieve with that code.

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40