Hi,
I am using Asp.Net Core 6. I am using JWT token in my project. I also want to use Cookie. But is it ok to use it this way? When I look at the browser cookies, the domain and expiry time do not appear.
C#
Code
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
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:SigningKey"]))
};
});
app.UseCookiePolicy(new CookiePolicyOptions()
{
MinimumSameSitePolicy = SameSiteMode.Lax,
HttpOnly = HttpOnlyPolicy.Always,
Secure = CookieSecurePolicy.Always,
ConsentCookie = new CookieBuilder
{
Name = "jwt-token",
Expiration = TimeSpan.MaxValue,
Domain = ".turkcell.com.tr",
}
});
C#
Code
TokenRepository
private const double EXPIRY_DURATION_MINUTES = 30;
public string BuildToken(string key, string issuer, LoginResponse user)
{
var claims = new[]
{
new Claim("Username", user.Username),
new Claim("IsAgent", user.IsAgent.ToString()),
new Claim("IsMasterAgent", user.IsMasterAgent.ToString()),
new Claim("Oid", user.Oid.ToString()),
};
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
expires: DateTime.Now.AddMinutes(EXPIRY_DURATION_MINUTES), signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}
public bool ValidateToken(string key, string issuer, string audience, string token)
{
var mySecret = Encoding.UTF8.GetBytes(key);
var mySecurityKey = new SymmetricSecurityKey(mySecret);
var tokenHandler = new JwtSecurityTokenHandler();
try
{
tokenHandler.ValidateToken(token,
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = issuer,
ValidAudience = issuer,
IssuerSigningKey = mySecurityKey,
}, out SecurityToken validatedToken);
}
catch
{
return false;
}
return true;
}