using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Web;
|
using System.IdentityModel.Tokens.Jwt;
|
using System.Security.Claims;
|
using System.Text;
|
using Microsoft.IdentityModel.Tokens;
|
|
namespace WebAPI.Utility
|
{
|
public static class JWTHelper
|
{
|
static JWTHelper()
|
{
|
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
|
}
|
|
// 秘钥
|
private const string SecretKey = "8sK2pR9vFg5tHjNm7qWaEe4dUcxZbL$S6y";
|
private static readonly SymmetricSecurityKey _securityKey =
|
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));
|
|
// 签发 Token
|
public static string GenerateToken(string userId, string userName, string HCampanyName)
|
{
|
var claims = new[]
|
{
|
new Claim(ClaimTypes.NameIdentifier, userId),
|
new Claim(ClaimTypes.Name, userName),
|
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
};
|
|
var credentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256);
|
|
var token = new JwtSecurityToken(
|
issuer: "zjzyms",
|
audience: HCampanyName,
|
claims: claims,
|
expires: DateTime.UtcNow.AddHours(2), // 两小时过期时间
|
signingCredentials: credentials
|
);
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
}
|
|
// 验证 Token 并返回 ClaimsPrincipal
|
public static ClaimsPrincipal ValidateToken(string token, string HCampanyName)
|
{
|
var handler = new JwtSecurityTokenHandler();
|
|
var parameters = new TokenValidationParameters
|
{
|
ValidateIssuer = true,
|
ValidIssuer = "zjzyms",
|
|
ValidateAudience = true,
|
ValidAudience = HCampanyName,
|
|
ValidateIssuerSigningKey = true,
|
IssuerSigningKey = _securityKey,
|
|
ValidateLifetime = true,
|
ClockSkew = TimeSpan.Zero, // 不允许时间误差
|
};
|
|
|
try
|
{
|
var principal = handler.ValidateToken(token, parameters, out var validatedToken);
|
return principal;
|
}
|
catch
|
{
|
return null;
|
}
|
}
|
}
|
}
|