码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-03-02 16:47:07      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

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验证

标签:

原文地址:http://www.cnblogs.com/CanFly/p/4308983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!