1、优化消息排序逻辑 2、新增加载历史消息 3、修复已知问题 后端: 1、优化消息排序逻辑 2、增加用户信息缓存机制 3、修改日期类型为DateTimeOffset改善时区信息丢失问题 3、修复了已知问题 数据库: 1、新增SequenceId字段用于消息排序 2、新增ClientMsgId字段用于客户端消息回执
56 lines
1.9 KiB
C#
56 lines
1.9 KiB
C#
using IM_API.Interface.Services;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace IM_API.Services
|
|
{
|
|
public class JWTService : IJWTService
|
|
{
|
|
private readonly IConfiguration _config;
|
|
private readonly string _key;
|
|
private readonly string _issuer;
|
|
private readonly string _audience;
|
|
private readonly int _accessMinutes;
|
|
|
|
public JWTService(IConfiguration config)
|
|
{
|
|
_config = config;
|
|
_key = _config["Jwt:Key"]!;
|
|
_issuer = _config["Jwt:Issuer"]!;
|
|
_audience = _config["Jwt:Audience"]!;
|
|
_accessMinutes = int.Parse(_config["Jwt:AccessTokenMinutes"] ?? "15");
|
|
}
|
|
|
|
public string GenerateAccessToken(IEnumerable<Claim> claims, DateTime expiresAt)
|
|
{
|
|
var keyBytes = Encoding.UTF8.GetBytes(_key);
|
|
var creds = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: _issuer,
|
|
audience: _audience,
|
|
claims: claims,
|
|
expires: expiresAt,
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
|
|
public (string token, DateTime expiresAt) CreateAccessTokenForUser(int userId, string username, string role)
|
|
{
|
|
var expiresAt = DateTime.Now.AddMinutes(_accessMinutes);
|
|
var claims = new[]
|
|
{
|
|
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
|
|
new Claim(ClaimTypes.Name, username),
|
|
new Claim(ClaimTypes.Role, role)
|
|
};
|
|
var token = GenerateAccessToken(claims, expiresAt);
|
|
return (token, expiresAt);
|
|
}
|
|
}
|
|
}
|