如何从Web Api .Net中的AuthorizeAttribute检索POST参数?

时间:2017-08-07 20:49:42

标签: jquery asp.net-mvc post asp.net-web-api

我正在为我的Web Api .Net项目使用令牌的身份验证方法,所以我重写了这样的一些方法:

public class Authorizetest: System.Web.Http.AuthorizeAttribute
{
        public override void OnAuthorization(HttpActionContext actionContext)
    {
           if(Authorize(actionContext))
        {
            return;
        }
        HandleUnauthorizedRequest(actionContext);  
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        base.HandleUnauthorizedRequest(actionContext);
    }

    private bool Authorize(HttpActionContext actionContext)
    {         
        try
        {                           
            var context = new HttpContextWrapper(HttpContext.Current);
            HttpRequestBase request = context.Request;              
            string token = request.Params["Token"];
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

我正在以这种方式使用装饰器[Authorizetest]

[Authorizetest]
    public class DoActionController : ApiController
        {
            [HttpPost]
            public Display DoSomething(Parameter param)
            {
                //do something
                return display;
            }
    }

但是request.Params正在返回null但是在DoSomething方法中,我从Parameter获得了值。

我也尝试过这样的事情:(基于this page

    HttpRequestBase request = actionContext.RequestContext.HttpContext.Request;
    string token = request.Params["Token"];

,但无法检索通过POST方法发送的任何值。

我正在使用JQuery发送数据

$.ajax({
                type: 'POST',
                url: '/DoSomething',
                data: JSON.stringify({ "Token": "xxxxxxxxx"}),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                },
                fail:function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });

如何检索DoSomething中发送给Authorizetest class的数据?

1 个答案:

答案 0 :(得分:1)

Auth Tokens应该在请求的标头中发送,然后由Authorize Attribute提取,如果打算将其用于授权。在模型绑定器有机会填充模型之前读取请求体可能会产生负面影响。

var token = "xxxxxxxxx";
$.ajax({    
    type: 'POST',
    url: '/DoSomething',
    data: JSON.stringify({ "SomeProperty": "SomeValue"}),
    contentType: 'application/json; charset=utf-8',
    beforeSend: function (xhr) {
        /* Authorization header */
        xhr.setRequestHeader("Authorization", "Token " + token);        
    },
    success: function (data) {
    },
    fail:function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

然后在服务器上访问它

public class Authorizetest : System.Web.Http.AuthorizeAttribute {
    public override void OnAuthorization(HttpActionContext actionContext) {
        if (Authorize(actionContext)) {
            return;
        }
        HandleUnauthorizedRequest(actionContext);
    }

    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {
        base.HandleUnauthorizedRequest(actionContext);
    }

    private bool Authorize(HttpActionContext actionContext) {
        try {
            var auth = actionContext.Request.Headers.Authorization;
            if (auth != null) {
                var scheme = auth.Scheme; //Should be Token, otherwise fail
                var token = auth.Parameter;
                //Validate your token and set your principal
                IPrincipal user = GetUser(token);
                if (user != null) {
                    SetPrincipal(user);
                    return true;
                }
            }
            return false;
        } catch (Exception) {
            return false;
        }
    }

    private IPrincipal GetUser(string token) {
        throw new NotImplementedException(); //Put your implementation here
    }

    private void SetPrincipal(System.Security.Principal.IPrincipal principal) {
        if (principal != null) {
            System.Threading.Thread.CurrentPrincipal = principal;
            if (System.Web.HttpContext.Current != null) {
                System.Web.HttpContext.Current.User = principal;
            }
        }
    }
}