类库先安装JWT的包,看下面的图
//创建Token
var token = JWTHelper.Create<JWTToken>(new JWTToken
{
SessionID = Guid.NewGuid().ToString("N"),
UserID = user.ID,
LoginIP = WebHelper.GetIP(),
LoginAt = DateTime.Now,
ExpiryAt = DateTime.Now.AddDays(1)
});
$.ajax({
type: "POST",
contentType: "application/json",
beforeSend: function (xrh) {
xrh.setRequestHeader("token", token);
},
data: data
});
JWTToken jwtToken = TokenVerification(actionContext);
/// <summary>
/// Token令牌验证
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
private JWTToken TokenVerification(HttpActionContext actionContext)
{
// 获取token
var luck_api_token = GetApiToken(actionContext);
if (!string.IsNullOrEmpty(luck_api_token))
{
JWTToken jwtToken = JWTHelper.Get<JWTToken>(luck_api_token);
if (jwtToken != null)
{
return jwtToken;
}
else
{
throw new CustomValidException("无效令牌", "-1");
}
}
else
{
throw new CustomValidException("无效令牌", "-1");
}
}
/// <summary>
/// Header获取健值
/// </summary>
/// <param name="actionContext"></param>
/// <param name="key"></param>
/// <returns></returns>
private string GetHeaderValues(HttpActionContext actionContext, string key)
{
IEnumerable<string> values;
actionContext.Request.Headers.TryGetValues(key, out values);
if (values != null && values.Any())
{
return values.FirstOrDefault();
}
else
return null;
}
/// <summary>
/// 获取AccessToken值
/// </summary>
/// <param name="actionContext"></param>
/// <returns></returns>
private string GetApiToken(HttpActionContext actionContext)
{
return GetHeaderValues(actionContext, "token");
}
<!-- Jwt 默认key-->
<add key="TokenSecret" value="jwt_key_2000_01_01"/>
public class JWTHelper
{
private readonly static string TOKEN_SECRET = ConfigurationManager.AppSettings["TokenSecret"].ToString();
/// <summary>
/// 创建token票据
/// </summary>
public static string Create(Dictionary<string, object> payload, string secret = "")
{
secret = string.IsNullOrWhiteSpace(secret) ? TOKEN_SECRET : secret;
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
return token;
}
/// <summary>
/// 创建token票据
/// </summary>
public static string Create<T>(T model, string secret = "") where T : JWTToken
{
secret = string.IsNullOrWhiteSpace(secret) ? TOKEN_SECRET : secret;
if (string.IsNullOrWhiteSpace(model.SessionID))
{
return "";
}
IJsonSerializer serializer = new JWTJsonSerializer();
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(model, secret);
return token;
}
/// <summary>
/// 配置
/// </summary>
private static IJwtDecoder Decoder()
{
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
return decoder;
}
/// <summary>
/// 返回token ->Json 键值对
/// </summary>
public static string Get(string token, string secret = "")
{
secret = string.IsNullOrWhiteSpace(secret) ? TOKEN_SECRET : secret;
IJwtDecoder decoder = Decoder();
var json = decoder.Decode(token, secret, verify: true);
return json;
}
/// <summary>
/// 获取token票据 解密实体
/// </summary>
public static T Get<T>(string token, string secret = "") where T : JWTToken
{
try
{
secret = string.IsNullOrWhiteSpace(secret) ? TOKEN_SECRET : secret;
IJwtDecoder decoder = Decoder();
var resultModel = decoder.DecodeToObject<T>(token, secret, verify: true);
return resultModel;
}
catch
{
return default(T);
}
}
}