add(refreshTokenService):完善刷新令牌服务
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.21" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.21">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
@@ -19,7 +20,9 @@
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.3" />
|
||||
<PackageReference Include="StackExchange.Redis" Version="2.9.32" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace IM_API.Interface.Services
|
||||
{
|
||||
public interface IJWTService
|
||||
{
|
||||
/// <summary>
|
||||
/// 生成用户凭证
|
||||
/// </summary>
|
||||
/// <param name="claims">负载</param>
|
||||
/// <param name="expiresAt">过期时间</param>
|
||||
/// <returns></returns>
|
||||
string GenerateAccessToken(IEnumerable<Claim> claims, DateTime expiresAt);
|
||||
/// <summary>
|
||||
/// 创建用户凭证
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
(string token, DateTime expiresAt) CreateAccessTokenForUser(int userId,string username,string role);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace IM_API.Interface.Services
|
||||
{
|
||||
public interface IRefreshTokenService
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建刷新令牌
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> CreateRefreshTokenAsync(int userId, CancellationToken ct = default);
|
||||
/// <summary>
|
||||
/// 验证刷新令牌
|
||||
/// </summary>
|
||||
/// <param name="token">刷新令牌</param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task<(bool ok, int userId)> ValidateRefreshTokenAsync(string token, CancellationToken ct = default);
|
||||
/// <summary>
|
||||
/// 删除更新令牌
|
||||
/// </summary>
|
||||
/// <param name="token">刷新令牌</param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task RevokeRefreshTokenAsync(string token, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
|
||||
using IM_API.Configs;
|
||||
using IM_API.Models;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using StackExchange.Redis;
|
||||
using System.Text;
|
||||
|
||||
namespace IM_API
|
||||
{
|
||||
@@ -16,14 +20,74 @@ namespace IM_API
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
||||
.Build();
|
||||
string conStr = builder.Configuration.GetConnectionString("DefaultConnection")!;
|
||||
|
||||
string conStr = configuration.GetConnectionString("DefaultConnection")!;
|
||||
string redisConStr = configuration.GetConnectionString("Redis");
|
||||
//注入数据库上下文
|
||||
builder.Services.AddDbContext<ImContext>(options =>
|
||||
{
|
||||
options.UseMySql(conStr,ServerVersion.AutoDetect(conStr));
|
||||
});
|
||||
//注入redis
|
||||
var redis = ConnectionMultiplexer.Connect(redisConStr);
|
||||
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
|
||||
|
||||
builder.Services.AddAllService(configuration);
|
||||
|
||||
builder.Services.AddSignalR();
|
||||
//允许所有来源(跨域)
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddDefaultPolicy(policy =>
|
||||
{
|
||||
policy.AllowAnyHeader()
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyOrigin()
|
||||
.AllowAnyOrigin();
|
||||
});
|
||||
});
|
||||
//凭证处理
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
//https非必须
|
||||
options.RequireHttpsMetadata = false;
|
||||
//保存token
|
||||
options.SaveToken = true;
|
||||
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
|
||||
{
|
||||
//验证签发者
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = configuration["Jwt:Issuer"],
|
||||
//验证受众
|
||||
ValidateAudience = true,
|
||||
ValidAudience = configuration["Jwt:Audience"],
|
||||
//验证签名密钥
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"])),
|
||||
//时间偏差容忍
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30)
|
||||
|
||||
|
||||
};
|
||||
//websocket token凭证处理
|
||||
options.Events = new JwtBearerEvents {
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
var accessToken = context.Request.Query["access_token"];
|
||||
if (!string.IsNullOrEmpty(accessToken))
|
||||
{
|
||||
context.Token = accessToken;
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
@@ -41,6 +105,7 @@ namespace IM_API
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
app.UseAuthentication();
|
||||
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,15 @@
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Jwt": {
|
||||
"Key": "change_this_super_secret_key_in_prod",
|
||||
"Issuer": "IMDemo",
|
||||
"Audience": "IMClients",
|
||||
"AccessTokenMinutes": 15,
|
||||
"RefreshTokenDays": 30
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=frp-era.com;Port=26582;Database=IM;User=product;Password=12345678;"
|
||||
"DefaultConnection": "Server=frp-era.com;Port=26582;Database=IM;User=product;Password=12345678;",
|
||||
"Redis": "192.168.5.100:6379"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user