2

I am working on an authentication method using a token for me Web Api .Net project, so I am overriding some methods like this:

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;
        }
    }
}

I am using the decorator [Authorizetest] on this way:

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

But the request.Params is returning null however in the DoSomething method I get the value from Parameter.

I also have tried something like: (based on this page)

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

, but it's not possible to retrieve any value sent through the POST method.

I am using JQuery to send the data

$.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);
                }
            });

How can I retrieve the data sent to DoSomething in the Authorizetest class?

8
  • I think you need to rephrase your question. It's not very clear. Commented Aug 7, 2017 at 20:50
  • @Difster, Thanks, I've changed the question a little bit I hope it's clearer Commented Aug 7, 2017 at 20:59
  • You've already got the data that is being sent. Why would you need to retrieve what you already sent? It's in your data variable. Commented Aug 7, 2017 at 21:03
  • @Jamo that is because what you seek is in the body of the request, not Params. This appears to be an XY problem. What is the ultimate goal you are trying to achieve? Commented Aug 7, 2017 at 21:06
  • Tokens should be send in the HEADER of the request and then extracted by the Authorize Attribute if the intention is to use it for auth. Reading the request body before the model binder has a chance to populate models can have negative effects. Commented Aug 7, 2017 at 21:09

1 Answer 1

4

Auth Tokens should be sent in the header of the request and then extracted by the Authorize Attribute if the intention is to use it for authorization. Reading the request body before the model binder has a chance to populate models can have negative effects.

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);
    }
});

Then access it on the server

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;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That's what I was looking for! +1!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.