造成该问题的原因的原因是ASP MVC 新版的JWT包的需要传四个参数了。具体如下:
//私钥 web.config中配置
private static string secret = ConfigurationManager.AppSettings["Secret"].ToString();
/// <summary>
/// 生成JwtToken
/// </summary>
/// <param name="payload">不敏感的用户数据</param>
/// <returns></returns>
public static string SetJwtEncode(Dictionary<string, object> payload)
{
//格式如下
//var payload = new Dictionary<string, object>
//{
// { "username","admin" },
// { "pwd", "claim2-value" }
//};
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JWT.Serializers.JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
return token;
}
/// <summary>
/// 根据jwtToken 获取实体
/// </summary>
/// <param name="token">jwtToken</param>
/// <returns></returns>
public static UserInfo GetJwtDecode(string token)
{
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
var algorithm = new HMACSHA256Algorithm();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var userInfo = decoder.DecodeToObject<UserInfo>(token, secret, verify: true);//token为之前生成的字符串
return userInfo;
}
catch (TokenExpiredException)
{
UserInfo s = new UserInfo();
s.userName = "超时";
return s;
}
catch (SignatureVerificationException)
{
UserInfo s = new UserInfo();
s.userName = "签名验证失败,数据可能被篡改");
return s;
}
}