81 lines
2.7 KiB
C#
81 lines
2.7 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Text;
|
|
using System.Security.Claims;
|
|
|
|
namespace CompetitionAPI
|
|
{
|
|
public class TokenValidationService
|
|
{
|
|
private readonly string _secretKey;
|
|
private readonly string _issuer;
|
|
|
|
public TokenValidationService(string secretKey, string issuer)
|
|
{
|
|
_secretKey = secretKey;
|
|
_issuer = issuer;
|
|
}
|
|
|
|
public bool ValidateToken(string token)
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var key = Encoding.ASCII.GetBytes(_secretKey);
|
|
|
|
try
|
|
{
|
|
tokenHandler.ValidateToken(token, new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true,
|
|
ValidIssuer = _issuer,
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(key),
|
|
ValidateAudience = false, // 可选:是否验证 Audience
|
|
ValidateLifetime = true, // 是否验证 Token 是否过期
|
|
ClockSkew = TimeSpan.Zero // 设置时间偏差
|
|
}, out var validatedToken);
|
|
|
|
if (validatedToken != null)
|
|
{
|
|
var model = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)validatedToken).Claims;
|
|
// 从旧token中提取用户信息
|
|
var userId = model.First(claim => claim.Type == ClaimTypes.NameIdentifier).Value;
|
|
var roleId = model.First(claim => claim.Type == ClaimTypes.Role).Value;
|
|
if (roleId == "2")
|
|
{
|
|
Competition.Mysql.BLL.admin_user bll = new Competition.Mysql.BLL.admin_user();
|
|
var user_model = bll.GetModel(userId);
|
|
if (user_model != null)
|
|
{
|
|
if (user_model.r4 == token)
|
|
{
|
|
return true;
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Token 验证失败
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|