WEBAPI使用过滤器对API接口进行验证

Posted 强大的程序猿人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WEBAPI使用过滤器对API接口进行验证相关的知识,希望对你有一定的参考价值。

用户登录控制器:[ActionFilter]自定义过滤器

用户信息:var userData = new JObject();
                   userData.Add("account", account);
                   userData.Add("password", password);
                   userData.Add("accountType",2);

生成用户登录的凭据:FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, account, DateTime.Now, DateTime.Now.AddMinutes(10),
         true, JsonConvert.SerializeObject(userData), FormsAuthentication.FormsCookiePath);

                            string ticString = FormsAuthentication.Encrypt(ticket);

 

设置AJAX请求的请求头:内容为登录时生成的凭证

$.ajax("/api/Supervisor/GetSupervisorList", {
            method: "GET",
            data: {
                account: obj.account || "",
                loginSession: obj.loginSession || "",
                pageNo: obj.pageNo || 1,
                keyword: obj.keyword || ""
            },//heads: {Authorization: "Basic " + obj.loginSession},
            beforeSend: function (xhr) {
                //发送ajax请求之前向http的head里面加入验证信息
                xhr.setRequestHeader(‘Authorization‘, ‘Basic ‘ + (obj.loginSession || ""));
            }})

 

[ActionFilter]自定义过滤器:必须继承ActionFilterAttribute

 public class ActionFilter : ActionFilterAttribute
    {
        private string _requestId;

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            //获取返回消息数据
            var response =

                actionExecutedContext.Response.Content.ReadAsAsync(
                    actionExecutedContext.ActionContext.ActionDescriptor.ReturnType);
        }
public override void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);
            var auther = actionContext.Request.Headers.Authorization;
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                return;
            }
            if (auther == null)
            {
                //actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                    new {messages = "登录已过期,请重新登录", resultCode = 1});
                //HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
            }
            else
            {
                if (auther.Scheme == "Basic" && !string.IsNullOrEmpty(auther.Parameter))
                {
                    var userData = Functions.JudgeSession(auther.Parameter.Trim());
                    if (userData == null)
                    {
                        //actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
                        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                            new { messages = "登录已过期,请重新登录", resultCode = 1 });
                       // HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
                    }
                    else
                    {

                     //修改API接口参数
                        actionContext.ActionArguments["account"] = userData.GetValue("account").ToString();
                        if (actionContext.ActionArguments.ContainsKey("accounType"))
                        {

                            actionContext.ActionArguments["account"] = userData.GetValue("accounType").ToString();
                        }

                    }
                }
            }}
        }

解密登录凭据,获取用户数据:

   public static JObject  JudgeSession(string sessionid) //判断session是否过期
        {
            try
            {
                
                var formsAuthenticationTicket = FormsAuthentication.Decrypt(sessionid);
                if (formsAuthenticationTicket == null)
                {
                    return null;
                }
                if (formsAuthenticationTicket.Expired)
                {
                    return null;
                }
                return JsonConvert.DeserializeObject<JObject>(formsAuthenticationTicket.UserData);
            }
            catch (Exception e)
            {
                return null;
            }
        }

 


























































































以上是关于WEBAPI使用过滤器对API接口进行验证的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Web API 来对 MVC 应用程序进行身份验证

Web API接口 安全验证

Web API接口 安全验证

WebApi中过滤器的AOP实现方式

Web API过滤器

使用令牌 WebAPI 对 MVC 应用程序进行身份验证