Home > Mobile >  Browser is not setting cookies after Response.Cookies.Append() - ASP.net core 6 webAPI
Browser is not setting cookies after Response.Cookies.Append() - ASP.net core 6 webAPI

Time:09-15

I have this code in my webAPI project:

var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Expires = newRefreshToken.Expires
            };

Response.Cookies.Append("someKey", "someVal", cookieOptions);

On a following browser response, I get this:

set-cookie: someKey=someVal; expires=Thu, 15 Sep 2022 07:02:31 GMT; path=/; httponly

But the browser does not set the cookies as seen in the application tab of the dev tools.

How do I make sure that the cookies get set?

Edit: Here is my Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlite(
        builder.Configuration.GetSection("ConnectionStrings:DefaultConnection").Value
    );
});
builder.Services.AddScoped<IAuthRepo, AuthRepo>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(
                    builder.Configuration.GetSection("AppSettings:Token").Value)),
            ValidateIssuer = false,
            ValidateAudience = false
        }
    );
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        builder =>
        {
            builder.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
});

var app = builder.Build();

app.UseCors();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

CodePudding user response:

try this:

var cookieOptions = new CookieOptions
    {
       HttpOnly = true,
       Expires = newRefreshToken.Expires,
       IsEssential = true
     };

Response.Cookies.Append("someKey", "someVal", cookieOptions);

  • Related