Files
QuotifyBE/Controllers/GeneralUseHelperFunctions.cs
eee4 1da5e47b88 fix: revert passing password hash for jwt generation
builder in Program.cs is not aware of it, so [Authorize] decorator can't
be provided data necessary to validate requests which contain JWT with
password
2025-07-15 18:00:20 +02:00

64 lines
2.1 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
namespace QuotifyBE.Controllers;
public class GeneralUseHelpers(ApplicationDbContext db, IConfiguration appsettings)
{
private readonly ApplicationDbContext _db = db;
private readonly IConfiguration _appsettings = appsettings;
async public Task<User?> GetUserFromEmail(string email)
{
return await _db.Users.FirstOrDefaultAsync(e => e.Email == email);
}
public string HashWithSHA512(string s)
{
using (var sha512 = SHA512.Create())
{
byte[] bytes = Encoding.ASCII.GetBytes(s);
byte[] hash = sha512.ComputeHash(bytes);
string hashstring = BitConverter.ToString(hash).Replace("-", "").ToLower();
return hashstring;
}
}
public string GenerateJwtToken(string username)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(
// JwtSecret won't be null here - otherwise Program.cs wouldn't start
_appsettings["JwtSecret"]!
)
);
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _appsettings["DomainName"]!,
audience: _appsettings["DomainName"]!,
claims: claims,
// https://stackoverflow.com/questions/21978658/invalidating-json-web-tokens#comment45057142_23089839
// small validity timeframe is important for invalidating tokens after a user changed their password
expires: DateTime.Now.AddMinutes(5),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}