WebAPI Token 验证
Posted 那么天涯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 验证的主要内容,如果未能解决你的问题,请参考以下文章