Update managing api security
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
using Managing.Domain.Users;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Managing.Domain.Users;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Managing.Api.Authorization;
|
||||
|
||||
@@ -16,21 +16,31 @@ public interface IJwtUtils
|
||||
public class JwtUtils : IJwtUtils
|
||||
{
|
||||
private readonly string _secret;
|
||||
private readonly string? _issuer;
|
||||
private readonly string? _audience;
|
||||
|
||||
public JwtUtils(IConfiguration config)
|
||||
{
|
||||
_secret = config.GetValue<string>("Jwt:Secret");
|
||||
_secret = config.GetValue<string>("Jwt:Secret")
|
||||
?? throw new InvalidOperationException("JWT secret is not configured.");
|
||||
_issuer = config.GetValue<string>("Authentication:Schemes:Bearer:ValidIssuer");
|
||||
_audience = config.GetValue<string>("Authentication:Schemes:Bearer:ValidAudiences");
|
||||
}
|
||||
|
||||
public string GenerateJwtToken(User user, string publicAddress)
|
||||
{
|
||||
// generate token that is valid for 15 minutes
|
||||
// Generate token that is valid for 15 days (as per original implementation)
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_secret);
|
||||
var key = Encoding.UTF8.GetBytes(_secret); // Use UTF8 consistently with Program.cs
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[] { new Claim("address", publicAddress) }),
|
||||
Expires = DateTime.UtcNow.AddDays(15),
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
||||
Issuer = _issuer, // Include issuer if configured
|
||||
Audience = _audience, // Include audience if configured
|
||||
SigningCredentials = new SigningCredentials(
|
||||
new SymmetricSecurityKey(key),
|
||||
SecurityAlgorithms.HmacSha256Signature)
|
||||
};
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
@@ -42,7 +52,7 @@ public class JwtUtils : IJwtUtils
|
||||
return null;
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(_secret);
|
||||
var key = Encoding.UTF8.GetBytes(_secret); // Use UTF8 consistently with Program.cs
|
||||
try
|
||||
{
|
||||
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
||||
|
||||
Reference in New Issue
Block a user