在前后端分離的項目里,我們請求接口的流程一般是:
- 用戶使用用戶名密碼登錄
- 信息正確,接口返回token
- 請求需要登錄驗證的接口,將token放到header里一起請求接口
這里介紹一下,在webapi項目里,token是怎么生成的?
- 項目的引用里,右鍵:管理NuGet程序包
- 搜索JWT,安裝即可,要注意項目的.NetFrameWork 要大於等於4.6
- 代碼如下:
public class TokenInfo { public TokenInfo() { UserName = "jack.chen"; Pwd = "jack123456"; } public string UserName { get; set; } public string Pwd { get; set; } } public class TokenHelper { public static string SecretKey = "This is a private key for Server";//這個服務端加密秘鑰 屬於私鑰 private static JavaScriptSerializer myJson = new JavaScriptSerializer(); 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); } public static TokenInfo DecodeToken(string token) { try { var json = GetTokenJson(token); TokenInfo info = myJson.Deserialize<TokenInfo>(json); return info; } catch (Exception) { throw; } } 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; } } }
- 使用cookie也是一樣,用戶登錄之后,用特定的方法生成cookie,返回到瀏覽器,瀏覽器每次請求接口或者訪問頁面的時候,都會帶上cookie信息,用於身份驗證
c#生成cookie的方法
public class UserModel { public string UserName { get; set; } public string Pwd { get; set; } } public class CookieHelper { private static JavaScriptSerializer myJson = new JavaScriptSerializer(); /// <summary> /// 設置登錄信息cookie /// </summary> /// <param name="model"></param> public static void SetUserCookie(UserModel model) { FormsAuthentication.SetAuthCookie(model.UserName, false); string userStr = myJson.Serialize(model); //創建ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now + FormsAuthentication.Timeout, false, userStr); //加密 var cookieValue = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath }; //寫入cookie HttpContext.Current.Response.Cookies.Remove(cookie.Name); HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 獲取登錄信息的cookie /// </summary> /// <returns></returns> public static UserModel GetUserCookie() { var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (object.Equals(cookie, null) || string.IsNullOrEmpty(cookie.Value)) { return null; } try { var ticket = FormsAuthentication.Decrypt(cookie.Value); if (!object.Equals(ticket, null) && !string.IsNullOrEmpty(ticket.UserData)) { UserModel userData = myJson.Deserialize<UserModel>(ticket.UserData); return userData; } } catch (Exception) { } return null; } }