C# ASP.net中用到的JWT身份验证
C# ASP.net中用到的JWT身份验证
转载自:C# ASP.net中用到的JWT身份验证 - 简辞 - 博客园 (cnblogs.com)
1.先通过NuGet添加JWT
2.新建一个JwtHelp类
1 public class JwtHelp 2 { 3 4 //私钥 web.config中配置 5 //"GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; 6 private static string secret = "footmark"; 7 8 /// <summary> 9 /// 生成JwtToken 10 /// </summary> 11 /// <param name="payload">不敏感的用户数据</param> 12 /// <returns></returns> 13 public static string SetJwtEncode() 14 { 15 16 //格式如下 17 IDateTimeProvider provider = new UtcDateTimeProvider(); 18 var now = provider.GetNow(); 19 var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); 20 //过期时间 21 var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds); 22 23 var payload = new Dictionary<string, object> 24 { 25 { "exp", secondsSinceEpoch+3600 }, //3600秒后过期 26 { "username","admin" }, 27 { "password","123456" } 28 }; 29 30 IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); 31 IJsonSerializer serializer = new JsonNetSerializer(); 32 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); 33 IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); 34 35 var token = encoder.Encode(payload, secret); 36 return token; 37 } 38 39 /// <summary> 40 /// 根据jwtToken 获取实体 41 /// </summary> 42 /// <param name="token">jwtToken</param> 43 /// <returns></returns> 44 public static string GetJwtDecode(string token) 45 { 46 try 47 { 48 IJsonSerializer serializer = new JsonNetSerializer(); 49 IDateTimeProvider provider = new UtcDateTimeProvider(); 50 IJwtValidator validator = new JwtValidator(serializer, provider); 51 IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); 52 IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder); 53 //token为之前生成的字符串 54 var userInfo = decoder.DecodeToObject(token, secret, verify: true); 55 //此处json为IDictionary<string, object> 类型 56 string username = userInfo["username"].ToString(); //可获取当前用户名 57 return "OK"; 58 59 } 60 catch (TokenExpiredException) 61 { 62 Console.WriteLine("Token has expired"); 63 } 64 catch (SignatureVerificationException) 65 { 66 Console.WriteLine("Token has invalid signature"); 67 } 68 catch (Exception) 69 { 70 71 } 72 return "Error"; 73 } 74 }