88 lines
2.6 KiB
C#
88 lines
2.6 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using MilliSim.Common.Entities;
|
|
using MilliSim.Common.Models;
|
|
|
|
namespace MilliSim.Services.Infrastructure;
|
|
|
|
public interface IJwtService
|
|
{
|
|
string GenerateToken(User user);
|
|
ClaimsPrincipal? ValidateToken(string token);
|
|
}
|
|
|
|
public class JwtService : IJwtService
|
|
{
|
|
private readonly IConfiguration _config;
|
|
|
|
public JwtService(IConfiguration config)
|
|
{
|
|
_config = config;
|
|
}
|
|
|
|
public string GenerateToken(User user)
|
|
{
|
|
var secretKey = _config["Jwt:SecretKey"]!;
|
|
var issuer = _config["Jwt:Issuer"];
|
|
var audience = _config["Jwt:Audience"];
|
|
var expireDays = int.Parse(_config["Jwt:ExpireDays"] ?? "7");
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
|
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
|
new(ClaimTypes.Name, user.Username),
|
|
new(ClaimTypes.Role, user.Role.ToString()),
|
|
new("nickname", user.Nickname),
|
|
new("role", ((int)user.Role).ToString())
|
|
};
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: issuer,
|
|
audience: audience,
|
|
claims: claims,
|
|
expires: DateTime.Now.AddDays(expireDays),
|
|
signingCredentials: credentials
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
|
|
public ClaimsPrincipal? ValidateToken(string token)
|
|
{
|
|
try
|
|
{
|
|
var secretKey = _config["Jwt:SecretKey"]!;
|
|
var issuer = _config["Jwt:Issuer"];
|
|
var audience = _config["Jwt:Audience"];
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
|
|
var handler = new JwtSecurityTokenHandler();
|
|
|
|
var parameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidateAudience = true,
|
|
ValidateLifetime = true,
|
|
ValidateIssuerSigningKey = true,
|
|
ValidIssuer = issuer,
|
|
ValidAudience = audience,
|
|
IssuerSigningKey = key,
|
|
ClockSkew = TimeSpan.Zero
|
|
};
|
|
|
|
return handler.ValidateToken(token, parameters, out _);
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|