標籤:
1、原理是使用ActionFilterAttribute對請求進行攔截,對Cookies進行解密。登入則對使用者資訊進行加密儲存在Cookies中。
自訂身分識別驗證特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class FormAuthAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { try { if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0) {//過濾允許匿名訪問的action base.OnActionExecuting(actionContext); return; } var cookie = actionContext.Request.Headers.GetCookies();//擷取Cookies if (cookie == null || cookie.Count < 1) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); return; } FormsAuthenticationTicket ticket = null; //遍曆Cookies,擷取驗證Cookies並解密 foreach (var perCookie in cookie[0].Cookies) { if (perCookie.Name == FormsAuthentication.FormsCookieName) { ticket = FormsAuthentication.Decrypt(perCookie.Value); break; } } if (ticket == null) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); return; } // TODO: 添加其它驗證方法 base.OnActionExecuting(actionContext); } catch { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden); } } }
登入驗證API
[Route("Login")] [AllowAnonymous] public IHttpActionResult Login([FromBody]LoginModel model) { if (model.UserName.Equals("admin") && model.PassWord.Equals("123456")) { FormsAuthentication.SetAuthCookie(model.UserName, false); if (model.IsRememberMe) { HttpContext.Current.Response.SetCookie(new HttpCookie("UserName", model.UserName) { Expires = DateTime.Now.AddDays(7) }); } return Ok(); } else { return NotFound(); } //return Ok(); }
對需要登入才能訪問的Api添加 [FormAuth]特性。
Asp.Net Web Api 身分識別驗證之Form驗證