c#中token的使用方法實例
token的存在意義
這是我初略瞭解的token的存在意義
- 用戶使用用戶名密碼來請求服務器
- 服務器進行驗證用戶的信息
- 服務器通過驗證發送給用戶一個token
- 客戶端存儲token,並在每次請求時附送上這個token值
- 服務端驗證token值,並返回數據
使用方法
先安裝一個JWT,註意NetFramework的版本
創建一個工具類TokenInfo.cs
using JWT; using JWT.Algorithms; using JWT.Serializers; using System; using System.Collections.Generic; using System.Web; using System.Web.Script.Serialization; namespace ProjectLYG.Common { public class TokenInfo { public TokenInfo() { UserName = "j"; Pwd = "123456"; } public string UserName { get; set; } public string Pwd { get; set; } } public class TokenHelper { public static string SecretKey = "bqsid123k12s0h1d3uhf493fh02hdd102h9s3h38ff";//這個服務端加密秘鑰 屬於私鑰 private static JavaScriptSerializer myJson = new JavaScriptSerializer(); /// <summary> /// 生成Token /// </summary> /// <param name="M"></param> /// <returns></returns> public static string GenToken(TokenInfo M) { var payload = new Dictionary<string, dynamic> { {"UserName", M.UserName},//用於存放當前登錄人賬戶信息 {"UserPwd", M.Pwd}//用於存放當前登錄人登錄密碼信息 }; IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return encoder.Encode(payload, SecretKey); } /// <summary> /// 驗證Token /// </summary> /// <returns></returns> public static string DecodeToken() { //獲取request中的token string token = HttpContext.Current.Request.Headers["Authorization"]; //去掉前面的Bearer if (token != null && token.StartsWith("Bearer")) token = token.Substring("Bearer ".Length).Trim(); try { var json = GetTokenJson(token); TokenInfo info = myJson.Deserialize<TokenInfo>(json); return "Token is true"; } catch (TokenExpiredException) { return "Token has expired"; } catch (SignatureVerificationException) { return "Token has invalid signature"; } } public static string GetTokenJson(string token) { try { 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); var json = decoder.Decode(token, SecretKey, verify: true); return json; } catch (Exception) { throw; } } } }
使用方法
//生成Token TokenInfo tokenInfo = new TokenInfo(); tokenInfo.Pwd = password; tokenInfo.UserName = tel; string token = TokenHelper.GenToken(tokenInfo); ........ //token驗證 string tokenInfo = TokenHelper.DecodeToken(); ........
工具類已將返回的Request的token值提取出,無須傳值
到此這篇關於c#中token的使用方法實例的文章就介紹到這瞭,更多相關c# token內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!