zoukankan      html  css  js  c++  java
  • asp.net web api 权限验证的方法

    思路:客户端使用header或者form讲验证信息传入api,在权限验证过滤中进行处理,代码示例:

    定义过滤器

     public class ApiFilter1 : System.Web.Http.AuthorizeAttribute
        {
           
            protected override bool IsAuthorized(HttpActionContext actionContext)
            {
                var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
                //var userName = content.Request.Headers["loginName"];
                   
    
                var user = content.Request.Form["userName"];
                var password = content.Request.Form["password"];
                //return base.IsAuthorized(actionContext);
                //return userName == "wilson" && password == "123";
                return base.IsAuthorized(actionContext);
            }
    
            //public override void OnAuthorization(HttpActionContext actionContext)
            //{
            //    var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            //    var UserName = content.Request.Form["UserName"];
    
            //    //base.OnAuthorization(actionContext);
            //}
    
            protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
        }

    定义api方法

     [HttpPost]
            [ApiFilter1]
            public string GetUserById2(InputPara val)
            {
                return JsonConvert.SerializeObject(val);
            }

    ajax客户端调用示例

      function testAjax() {
            $.ajax({
                headers:{"loginName": "wilson", "password": "1234"},
                type: "post",
                url: "/api/user/GetUserById2",
                data: { "userName": "wilson", "password": "1234" },
                success: function (data) {
                    alert(JSON.stringify(data));
                }
            });
    
        }
    var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
    /*
    * 使用流写入的数据无法通过Form参数获取,只能通过流读取
    */
    using (MemoryStream ms = new MemoryStream())
    {
    content.Request.InputStream.CopyTo(ms);
    byte[] paraContent = ms.ToArray();
    Encoding encoding = Encoding.UTF8;
    string val = encoding.GetString(paraContent);
    }
  • 相关阅读:
    elasticsearch + kibana 安装
    JSON Web Token
    JConsole和VisualVM远程访问JMX
    DNS域名解析
    Spring Cloud(2)主要组件应用实例
    Docker(三):Docker入门教程-CentOS Docker 安装
    Spring Cloud(1)相关概念
    Zookeeper实现哨兵机制
    大数据学习笔记之初识Hadoop
    大数据学习笔记之大数据概述
  • 原文地址:https://www.cnblogs.com/weiweictgu/p/7102330.html
Copyright © 2011-2022 走看看