using Infrastructure;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using ZR.Admin.WebApi.Extensions;
using ZR.Model.System;
namespace ZR.Admin.WebApi.Framework
{
///
/// 2020-11-20
///
public class JwtUtil
{
///
/// 获取用户身份信息
///
///
///
public static LoginUser GetLoginUser(HttpContext httpContext)
{
string token = httpContext.GetToken();
if (!string.IsNullOrEmpty(token))
{
return ValidateJwtToken(ParseToken(token));
}
return null;
}
///
/// 生成token
///
///
///
///
public static string GenerateJwtToken(List claims, JwtSettings jwtSettings)
{
//JwtSettings jwtSettings = new();
//ConfigUtils.Instance.Bind("JwtSettings", jwtSettings);
var authTime = DateTime.Now;
var expiresAt = authTime.AddMinutes(jwtSettings.Expire);
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
claims.Add(new Claim("Audience", jwtSettings.Audience));
claims.Add(new Claim("Issuer", jwtSettings.Issuer));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Issuer = jwtSettings.Issuer,
Audience = jwtSettings.Audience,
IssuedAt = authTime,//token生成时间
Expires = expiresAt,
//NotBefore = authTime,
TokenType = "Bearer",
//对称秘钥,签名证书
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
///
/// 验证Token
///
///
public static TokenValidationParameters ValidParameters()
{
JwtSettings jwtSettings = new();
ConfigUtils.Instance.Bind("JwtSettings", jwtSettings);
if (jwtSettings == null || jwtSettings.SecretKey.IsEmpty())
{
return null;
}
var key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);
var tokenDescriptor = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,//是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
ClockSkew = TimeSpan.FromSeconds(30)
//RequireExpirationTime = true,//过期时间
};
return tokenDescriptor;
}
///
/// 从令牌中获取数据声明
///
/// 令牌
///
public static IEnumerable ParseToken(string token)
{
var tokenHandler = new JwtSecurityTokenHandler();
var validateParameter = ValidParameters();
token = token.Replace("Bearer ", "");
try
{
tokenHandler.ValidateToken(token, validateParameter, out SecurityToken validatedToken);
var jwtToken = tokenHandler.ReadJwtToken(token);
return jwtToken.Claims;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// return null if validation fails
return null;
}
}
///
/// jwt token校验
///
///
///
public static LoginUser ValidateJwtToken(IEnumerable jwtToken)
{
try
{
//var userId = jwtToken.FirstOrDefault(x => x.Type == "primarysid").Value;
//var userName = jwtToken.FirstOrDefault(x => x.Type == "unique_name").Value;
var userData = jwtToken.FirstOrDefault(x => x.Type == ClaimTypes.UserData).Value;
LoginUser loginUser = JsonConvert.DeserializeObject(userData);
return loginUser;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
}
}