WebAPI Token 驗證
WebAPI Token 驗證
登錄端
//HttpContext.Current.Session.Timeout = 10;
////生成Ticket
//FormsAuthenticationTicket token = new FormsAuthenticationTicket(0,req.LUsername,DateTime.Now,DateTime.Now.AddMinutes(10),true,string.Format("{0}& {1}",req.LUsername,req.LUPassword),FormsAuthentication.FormsCookiePath);
//var Token = FormsAuthentication.Encrypt(token);
//HttpContext.Current.Session["UserName"] = req.LUsername;
//loginInfo.Ticket = Token;
過濾器
var authorization = actionContext.Request.Headers.Authorization; if ((authorization != null) && (authorization.Parameter != null)) { var encryptTicket = authorization.Parameter; if (ValidateTicket(encryptTicket)!=null) { userName = ValidateTicket(encryptTicket); } }
解密方法
private string ValidateTicket(string encryptTicket) { var strTicket = FormsAuthentication.Decrypt(encryptTicket).UserData; //從Ticket裏面獲取用戶名和密碼 var index = strTicket.IndexOf("&"); string strUser = strTicket.Substring(0, index); string strPwd = strTicket.Substring(index + 1); HttpContext.Current.Session["UserName"] = strUser; HttpContext.Current.Session["Token"] = strPwd; return strUser; }
//Ajax請求
function bookingList() { var token=‘@ViewBag.Token‘; $.ajax({ //提交數據的類型 POST GET type: "POST", //提交的網 址 url: "http://localhost:12426/api/Blocking/BlockingList", //提交的數據 data: { "SearchText": "" } , beforeSend : function(XHR){ XHR.setRequestHeader(‘Authorization‘, ‘BasicAuth ‘ +token); } , async: false,//false為同步,true為異步 //返回數據的 格式 datatype: "html",//"xml", "html", "script", "json", "jsonp", "text". //成功返回之後調用的函數 success: function (result) { for (var i = 0; i < result.TotalBlockingCount; i++) { //alert(result.blockDataList[i].MemberName); $("#txtContent").attr("value", result.blockDataList[i].MemberName); } }, //調用出錯執行的函數 error: function (XMLHttpRequest, textStatus, errorThrown) { //#3這個error函數調試時非常有用,如果解析不正確,將會彈出錯誤框 alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); // paser error; } }); }
WebAPI Token 驗證