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