I have to login methods on my website but i have a problem that when i login with normal Authentication i need to login in database like i have multiple servers i choose one i log in on one of those but the problem is the key because when i log in with database i need to store a claim that is the username so i can use on other stored procedures because to make two token is not a good solution how can i maintain to refresh the claim or maybe refresh the token so it doesn’t affect the log in
I tried to store it in headers but it didn’t, tried to make two Authentication tokens but that is to much complex and to many validation
Login:
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
var existingToken = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (!string.IsNullOrEmpty(existingToken))
{
var tokenStoreService = HttpContext.RequestServices.GetRequiredService<ITokenStoreService>();
tokenStoreService.AddTokenToBlacklist(existingToken);
}
// Retrieve the connection string for the user
var connectionString = GetUserConnectionString(user);
var token = GenerateJwtToken(user, connectionString, model.RememberMe);
return Ok(new { Token = token });
}
return Unauthorized(new { Result = "Invalid login attempt" });
}
return BadRequest(ModelState);
Token Generator:
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(kosovoTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(kosovoTime).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Actor, AesEncryptionHelper.Encrypt(connectionString)),
new Claim(ClaimTypes.GivenName, "")
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expiration = rememberMe ? kosovoTime.AddDays(7) : kosovoTime.AddDays(1);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
notBefore: kosovoTime,
expires: expiration,
signingCredentials: creds);
var tokenHandler = new JwtSecurityTokenHandler();
var tokenString = tokenHandler.WriteToken(token);
if (rememberMe)
{
var tokenStoreService = HttpContext.RequestServices.GetRequiredService<ITokenStoreService>();
tokenStoreService.SetExtendedExpiration(tokenString, expiration);
}
return tokenString;
Database LogIn:
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId == null)
{
return Unauthorized(new { Result = "User not found" });
}
var connectionDetails = await _context.Connections
.FirstOrDefaultAsync(c => c.ApplicationUserId == userId);
if (connectionDetails == null)
{
return BadRequest(new { Result = "No connection details found for the specified user" });
}
var decryptedPassword = AesEncryptionHelper.Decrypt(connectionDetails.Password);
var dynamicConnectionString = new SqlConnectionStringBuilder
{
DataSource = connectionDetails.Server,
InitialCatalog = connectionDetails.Database,
UserID = connectionDetails.Username,
Password = decryptedPassword,
TrustServerCertificate = true
}.ConnectionString;
var sql = $"EXEC [{connectionDetails.Database}].dbo.TryWebLogin @CurrentCulture, @OnlineVersion, @MacAddress, @Username, @Password";
try
{
using (var connection = new SqlConnection(dynamicConnectionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@CurrentCulture", model.CurrentCulture);
command.Parameters.AddWithValue("@OnlineVersion", model.OnlineVersion);
command.Parameters.AddWithValue("@MacAddress", model.MacAddress);
command.Parameters.AddWithValue("@Username", model.Username);
command.Parameters.AddWithValue("@Password", model.Password);
await connection.OpenAsync();
var result = await command.ExecuteScalarAsync();
if (result != null && Convert.ToInt32(result) == 1)
{
return Ok(new { Result = "Login successful" });
}
else
{
return Unauthorized(new { Result = "Invalid login attempt" });
}
}
}
}
catch (SqlException ex)
{
_logger.LogError(ex, "Connection failed");
return StatusCode(500, new { Result = "Connection failed" });
}
Vështrim Mulaku is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.