webapi之权限验证

webapi之权限验证

一.概念:

二.demo:

1.登录时生成token:

  FormsAuthenticationTicket token = new FormsAuthenticationTicket(0, account, DateTime.Now,
                  DateTime.Now.AddHours(1), true, account,
                  FormsAuthentication.FormsCookiePath);
                loginRltViewModel.TokenStr = FormsAuthentication.Encrypt(token);

2.global文件中配置:

 GlobalConfiguration.Configure(WebApiConfig.Register);

3.WebApiConfig文件中添加到过滤器中:

  config.Filters.Add(new RequestAuthorizeAttribute());//校验token

4.创建一个类文件用来校验token,此文件必须继承ActionFilterAttribute类:

    public class RequestAuthorizeAttribute : ActionFilterAttribute
    {

        //重写基类的验证方式,加入我们自定义的Ticket验证  前端 XHR.setRequestHeader('Authorization', 'BasicAuth ' + Ticket);
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext context)
        {
            base.OnActionExecuting(context);
            if (context.ActionDescriptor.ActionName != "CheckLogin")
            {
                bool checkRlt = false;
                var authorization = context.Request.Headers.Authorization;
                if ((authorization != null) && (authorization.Parameter != null))
                {
                    checkRlt = CheckToken(authorization.Parameter);
                }
                if (!checkRlt)
                {
                    context.Response = context.Request.CreateResponse(HttpStatusCode.OK, "Err:9001");       
                }
            }
        }

        public static bool CheckToken(string token)
        {
            if (HttpRuntime.Cache[token] != null)
            {
                return true;
            }
            return false;
        }
}

跳过验证的方法:  

比如登陆不需要验证,就可以在登陆的操作上增加[AllowAnonymous]特性

前提是需要如下代码

var customAttributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
            var isAllow = customAttributes.Any(x => x is AllowAnonymousAttribute);
if(isAllow)
{
//跳过
}else
{
//验证
}
原文地址:https://www.cnblogs.com/zlp520/p/9414793.html