webapi添加basic认证

啦啦啦啦啦啦 

   //base.OnAuthorization(),此方法内部,调用IsAuthorized()判断是否授权,如果未授权调用HandleUnauthorizedRequest()方法
    //base.IsAuthorized(),判断Principal、Identity是否为空,为空则未授权
    //base.HandleUnauthorizedRequest(),此方法内部创建Response,状态码401;
    //
    public class BasicAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {

            var authenticationHeader = actionContext.Request.Headers.Authorization;

            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count > 0
                || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count > 0)
            {//如果有AllowAnonymous特性,就不检查
                base.OnAuthorization(actionContext);
            }
            else if (authenticationHeader != null && authenticationHeader.Scheme == "Basic" && !string.IsNullOrEmpty(authenticationHeader.Parameter))
            {
                var userNameAndPassword = GetUserNameAndPassword(authenticationHeader.Parameter);
                //此处添加用户名密码校验逻辑
                if (userNameAndPassword.Item1 == "zhangsan" && userNameAndPassword.Item2 == "123")
                {
                    actionContext.RequestContext.Principal = null;//这里自己实现一下
                }
                else {
                    base.HandleUnauthorizedRequest(actionContext);
                }
            }
            else
            {
                base.HandleUnauthorizedRequest(actionContext);
            }

        }
        private Tuple<string, string> GetUserNameAndPassword(string authenticationParameter)
        {
            if (!string.IsNullOrWhiteSpace(authenticationParameter))
            {
                var data = Encoding.ASCII.GetString(Convert.FromBase64String(authenticationParameter)).Split(:);
                return new Tuple<string, string>(data[0], data[1]);
            }
            return null;
        }
    }

 

 添加Filter

        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            RegisterFilters(config.Filters);
        }
        public static void RegisterFilters(HttpFilterCollection filters)
        {
            filters.Add(new BasicAuthorize());
        }

webapi添加basic认证

上一篇:学习:API断点和条件记录断点和内存断点的配合


下一篇:win7安装 truffle