C
C#9mo ago
Commander

.NET 8 Simple Cookie Authentication

Hello, I am a bit confused about simple Cookie Authentication in .net 8 I have the following in my Program.cs:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(Constants.LoginTimeoutHours);
options.Cookie.IsEssential = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.None; // will make it SSL later
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.Name = "somename";
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.AccessDeniedPath = "/Home/AccessDenied";
});
...
app.UseAuthentication();
app.UseAuthorization();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(Constants.LoginTimeoutHours);
options.Cookie.IsEssential = true;
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.None; // will make it SSL later
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.Name = "somename";
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.AccessDeniedPath = "/Home/AccessDenied";
});
...
app.UseAuthentication();
app.UseAuthorization();
1 Reply
Commander
CommanderOP9mo ago
When someone logs in, this code is executed:
private async Task LogInAccount(UserAccount account, string activity)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Role, account.Type.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Sid, account.GetIdAsString()));
identity.AddClaim(new Claim(ClaimTypes.Name, account.Name));
identity.AddClaim(new Claim(Constants.AccessTokenClaim, GetAccessToken(account.GetIdAsString())));

var principal = new ClaimsPrincipal(identity);
var authProperties = new AuthenticationProperties();
authProperties.AllowRefresh = true;
authProperties.IsPersistent = true;
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);
}

private static string GetAccessToken(string userId)
{
var identity = new ClaimsIdentity(new List<Claim>
{
new Claim(Constants.AccessTokenSubClaim, userId)
});

byte[] byteArray = new byte[32];
RandomNumberGenerator.Create().GetBytes(byteArray);
var strKey = Encoding.UTF8.GetString(byteArray);
var bytes = Encoding.UTF8.GetBytes(strKey);
// This is the problem here ^ i intentionally generate a random key each time, because I want to check if I will get an error

var key = new SymmetricSecurityKey(bytes);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var now = DateTime.UtcNow;
var handler = new JwtSecurityTokenHandler();

var token = handler.CreateJwtSecurityToken(
Constants.JWTIssuer, Constants.JWTAudience, identity,
now, now.Add(TimeSpan.FromHours(Constants.LoginTimeoutHours)),
now, signingCredentials);

return handler.WriteToken(token);
}
private async Task LogInAccount(UserAccount account, string activity)
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Role, account.Type.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Sid, account.GetIdAsString()));
identity.AddClaim(new Claim(ClaimTypes.Name, account.Name));
identity.AddClaim(new Claim(Constants.AccessTokenClaim, GetAccessToken(account.GetIdAsString())));

var principal = new ClaimsPrincipal(identity);
var authProperties = new AuthenticationProperties();
authProperties.AllowRefresh = true;
authProperties.IsPersistent = true;
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);
}

private static string GetAccessToken(string userId)
{
var identity = new ClaimsIdentity(new List<Claim>
{
new Claim(Constants.AccessTokenSubClaim, userId)
});

byte[] byteArray = new byte[32];
RandomNumberGenerator.Create().GetBytes(byteArray);
var strKey = Encoding.UTF8.GetString(byteArray);
var bytes = Encoding.UTF8.GetBytes(strKey);
// This is the problem here ^ i intentionally generate a random key each time, because I want to check if I will get an error

var key = new SymmetricSecurityKey(bytes);
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var now = DateTime.UtcNow;
var handler = new JwtSecurityTokenHandler();

var token = handler.CreateJwtSecurityToken(
Constants.JWTIssuer, Constants.JWTAudience, identity,
now, now.Add(TimeSpan.FromHours(Constants.LoginTimeoutHours)),
now, signingCredentials);

return handler.WriteToken(token);
}
I intentionally made the key the cookie is signed with to be random each time, so I get it invalidated. I can create a cookie event, where I manually validate the cookie. But isn't there a build in way to do this? I am confused about what is the intented and proper way to validate these cookies.
Want results from more Discord servers?
Add your server