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