馬上要用做安卓APP了,前后端分離的,后台必然要寫WebAPI 來做操作,
但是API不可能給任何人使用,所以要加身份驗證來過濾非法請求,話不多說一起來看吧。
1.創建項目
2.創建AP控制器
3.廢話半天開始編碼(簡單登陸分配Token令牌)
前台代碼
@using (Html.BeginForm("Index", "Default", FormMethod.Post)) { <div> <input type="text" name="username" /> <input type="text" name="pwd" /> <input type="submit" value="登陸"> </div> }
控制器代碼
[HttpPost] public ActionResult Index(string username, string pwd) { if (IsTrue(username, pwd)) { //生成令牌 //重點在這里 //命名空間 System.Web.Security 參數分別問版本,Cookie名稱 ,當前時間,結束時間,是否持續為持續性Cookie(True,False),數據,Cookie存放路徑 System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(0, username, DateTime.Now, DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", username, pwd), System.Web.Security.FormsAuthentication.FormsCookiePath); //加密 string ticketNum = System.Web.Security.FormsAuthentication.Encrypt(ticket); if (ticketNum != null && ticketNum.Trim().Length > 0) { return RedirectToAction("Show", "Default", new { ticket = ticketNum }); } } else { } return View(); } public ActionResult Show(string ticket) { ViewBag.pp = ticket; return View(); } public bool IsTrue(string name, string pwd) { if (name == "123" && pwd == "123") { return true; } else { return false; } }
Show視圖的顯示
<body> Token: @ViewBag.pp </body>
就這么簡單Token加密的生成成功了 明天寫實際用法~不積跬步無以至千里,不計小流無以成江海~