在先後端分離的項目裏,咱們請求接口的流程通常是:web
這裏介紹一下,在webapi項目裏,token是怎麼生成的json
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的方法:c#
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; } }