using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Utility.Extensions;
using Microsoft.IdentityModel.Tokens;
namespace CoreCms.Net.Utility.Helper
{
///
/// Jwt帮助工具
///
public static class JwtTokenHelper
{
///
/// 创建Token(暂不使用)
///
///
public static string CreateJwt(CoreCmsUser userInfo)
{
//创建声明Token数组
var claim = new List {
new Claim(ClaimTypes.GivenName, userInfo.userName),
new Claim(ClaimTypes.Name, userInfo.nickName),
new Claim(JwtRegisteredClaimNames.Jti, userInfo.id.ToString()),
new Claim(ClaimTypes.Expiration, DateTime.Now.AddHours(1).ToString("yyyy-MM-dd HH:mm:ss")) };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yanglingcong@qq.com"));//密钥大小要超过128bt,最少要16位
//实例化一个token对象
//第一种方式
//var token = new JwtSecurityToken(claims: claim);
//第二种方式
var token = new JwtSecurityToken(
issuer: "kevin",//发起人:当前项目
audience: "kevin project",//订阅:我们需要谁去使用这个Token
claims: claim,//声明的数组
expires: DateTime.Now.AddHours(1),//当前时间加一小时,一小时后过期
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)//数字签名 第一部分是密钥,第二部分是加密方式
);
//生成token
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
}
///
/// 解析token
///
///
///
public static GetTokenModel AnalysisToken(string token)
{
//第一种直接用JwtSecurityTokenHandler提供的read方法
var jwtHander = new JwtSecurityTokenHandler();
JwtSecurityToken jwtSecurityToken = jwtHander.ReadJwtToken(token);
GetTokenModel tokenModel = new GetTokenModel();
var currentInfo = jwtSecurityToken.Claims;
if (currentInfo.Any())
{
tokenModel.UserName = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.MobilePhone)!.Value;
tokenModel.NickName = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Name)!.Value;
tokenModel.UserId = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.NameIdentifier)!.Value.ObjectToInt(0);
tokenModel.Expired = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Expired)!.Value.ObjectToInt(0);
var dt = DateTime.Now;
tokenModel.Expiration = currentInfo.FirstOrDefault(f => f.Type == ClaimTypes.Expiration)!.Value.ObjectToDate(dt);
if (dt > tokenModel.Expiration)
{
return null;
}
}
return tokenModel;
}
}
///
/// 获取token信息
///
public class GetTokenModel
{
///
/// 用户
///
public string UserName { get; set; }
///
/// 用户昵称
///
public string NickName { get; set; }
///
/// 用户序列
///
public int UserId { get; set; }
///
/// 有效时间分钟
///
public int Expired { get; set; }
///
/// 有效时间
///
public DateTime Expiration { get; set; }
}
}