add(refreshTokenService):完善刷新令牌服务
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
namespace IM_API.Services
|
||||
using IM_API.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace IM_API.Services
|
||||
{
|
||||
public class FriendService
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
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.UtcNow.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using IM_API.Interface.Services;
|
||||
using Microsoft.AspNetCore.Connections;
|
||||
using Newtonsoft.Json;
|
||||
using StackExchange.Redis;
|
||||
using System.Numerics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace IM_API.Services
|
||||
{
|
||||
public class RedisRefreshTokenService : IRefreshTokenService
|
||||
{
|
||||
private readonly ILogger<RedisRefreshTokenService> _logger;
|
||||
//redis数据库
|
||||
private readonly IDatabase _db;
|
||||
private IConfiguration configuration;
|
||||
//过期时长
|
||||
private readonly TimeSpan _refreshTTL;
|
||||
public RedisRefreshTokenService(ILogger<RedisRefreshTokenService> logger, IConnectionMultiplexer multiplexer, IConfiguration configuration)
|
||||
{
|
||||
_logger = logger;
|
||||
_db = multiplexer.GetDatabase();
|
||||
this.configuration = configuration;
|
||||
//设置refresh过期时间
|
||||
var days = int.Parse(this.configuration["Jwt:RefreshTokenDays"] ?? "30");
|
||||
_refreshTTL = TimeSpan.FromDays(days);
|
||||
}
|
||||
|
||||
private static string GenerateTokenStr()
|
||||
{
|
||||
var bytes = RandomNumberGenerator.GetBytes(32);
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
|
||||
public async Task<string> CreateRefreshTokenAsync(int userId, CancellationToken ct = default)
|
||||
{
|
||||
string token = GenerateTokenStr();
|
||||
var payload = new { UserId = userId,CreateAt = DateTime.Now};
|
||||
string json = JsonConvert.SerializeObject(payload);
|
||||
//token写入redis
|
||||
await _db.StringSetAsync(token,json,_refreshTTL);
|
||||
return token;
|
||||
}
|
||||
|
||||
public async Task RevokeRefreshTokenAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
await _db.KeyDeleteAsync(token);
|
||||
}
|
||||
|
||||
public async Task<(bool ok, int userId)> ValidateRefreshTokenAsync(string token, CancellationToken ct = default)
|
||||
{
|
||||
var json = await _db.StringGetAsync(token);
|
||||
if (json.IsNullOrEmpty) return (false,-1);
|
||||
try
|
||||
{
|
||||
var doc = JsonConvert.DeserializeObject<JsonElement>(json);
|
||||
var userId = doc.GetProperty("UserId").GetInt32();
|
||||
return (true,userId);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (false,-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user