這個例子是基於客戶端與webapi進行進行交互的身份認證,當然也適用於其他情況下的身份認證。
簡單的交互過程:
1.首先輸入用戶名、密碼進行登錄操作
2.服務器驗證用戶名、密碼的正確性,驗證通過之后,服務器對一個json字符串進行加密,加密的內容、加密方法可以自己確定。
本次我加密的內容主要是用戶名和登錄時間,可根據需求添加其他加密內容,加密方法就是采用DES加密。然后將加密的后的字符串(Token)返回給到客戶端,客戶端需要自己保存起來。
3.接下來,客戶端的每次請求都需要帶上這個Token。
4.對於客戶端的每次請求,服務器首先都要去獲取Token,檢查Token是否合法,並解密Token內容,檢查Token是否過期等。
Token格式
未加密之前的字符串是什么樣的呢,我這里是最簡單的格式,如下:
{ "username":"",//用戶名 "createtime":""//認證時間 }
登錄認證通過之后,把這個json格式的字符串進行加密生成字符串Token,返回給客戶端。
至於好處呢,服務器不需要保存會話狀態,不用擔心會話丟失,也可以減輕服務器壓力,然后利用這種方式也方便部署分布式服務,將一個服務拆分成多個小服務,減輕單台服務器的壓力。
DES加解密算法
這里只是一種加解密算法而已,根據需要自己選擇合適的算法。
const string DESKey = "sddsdds";//秘鑰 const string DESIV = "errtertet";//向量 //加密 public string EncryptDES(string ToEncrypt, string DESKey, string DESIV) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { //創建des實例 byte[] inputByteArray = Encoding.UTF8.GetBytes(ToEncrypt);//將需要加密的內容轉為字節 des.Key = ASCIIEncoding.ASCII.GetBytes(DESKey);//秘鑰 des.IV = ASCIIEncoding.ASCII.GetBytes(DESIV);//向量 System.IO.MemoryStream ms = new System.IO.MemoryStream();//創建流實例 using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) {//把輸出的內容通過第二個參數轉換(加密)饋送到第一個參數ms cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } //轉為Base64后輸出 string str = Convert.ToBase64String(ms.ToArray()); ms.Close(); return str;
} }
//解密
public string[] DecodeDES(string Paras, string DESKey, string DESIV) { string Str = ""; string[] Ret = new string[2] { "",""}; try { byte[] inputByteArray = Convert.FromBase64String(Paras); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(DESKey); des.IV = ASCIIEncoding.ASCII.GetBytes(DESIV); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } Str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); Ret[0] = "1"; Ret[1] =Str; } } catch (Exception ex) { Ret[0] = "-1"; Ret[1] = ex.ToString(); } finally { } return Ret; }