Asp.Net Web Api 身份验证之Form验证

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]特性。

posted on 2015-03-02 15:57  慧飞  阅读(635)  评论(0编辑  收藏  举报

导航