5

I am making a web api to work with a legacy system. This web api should work in the same way as the old one. The security is to send a security token along with each call. This means that i need to check the token before serving data. I have a method like this:

public List<User> Get(string id, string securityToken)
        {
            //ValidateToken(securityToken);
            return userRepository.LoadAll();
        }

And in my method i would like the validateToken() method to return a "Forbidden" httpresponse if i cant validate it. How do i go around doing this?

vcsjones
  • 138,677
  • 31
  • 291
  • 286
Brian Hvarregaard
  • 4,081
  • 6
  • 41
  • 77

3 Answers3

12

IHttpActionResult:

return StatusCode(HttpStatusCode.Forbidden);

Or:

return Content(HttpStatusCode.Forbidden, "message");

HttpResponseMessage:

return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "message");

See this example if you would like a custom controller to have Forbidden() implemented just like BadRequest() or any other response.

https://stackoverflow.com/a/28361376/3850405

Ogglas
  • 62,132
  • 37
  • 328
  • 418
11

You can use an HttpResponseMessage like so:

public HttpResponseMessage Get(string id, string securityToken)
{
    var forbidden = true;
    if (forbidden)
    {
        return this.Request.CreateResponse(HttpStatusCode.Forbidden);
    }
    return Ok(userRepository.LoadAll());
}

Using HttpResponseMessage allows you to return OK (an HTTP 200) with content, or an error.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • 14
    Thanks for the help! My api returns IHttpActionResult, therefore I need to use `return StatusCode(HttpStatusCode.Forbidden);` instead. – John Henckel Sep 08 '15 at 18:14
  • @JohnHenckel That's possible, too, however, for general design I think it may be a better choice to implement an FilterAttribute as Haney mentioned and use it wherever possible. It's modular, it scales and you can keep your repository and your controllers a bit more clean from boilerplate code. So the implementation from either of you may be useful, if complex logic is involved to decide whether the requester is authorised or not (in which filters may not work). – LFish Mar 06 '17 at 13:23
6

Typically you'd do the ValidateToken type call in an ActionFilterAttribute, returning the forbidden at that time, long before the Get method was called on the controller. You'd then apply that attribute to the controller or action method (or register it as a global action filter attribute if you need to authorize ALL calls).

Haney
  • 32,775
  • 8
  • 59
  • 68
  • 1
    +1 for this is probably the more correct way of doing this and using WebAPIs plumbing to make it reusable. – vcsjones May 19 '14 at 20:11
  • @vcsjones your answer is valid as well. The only reason I prefer this way is for the re-use since authorization tends to be a single scheme for > 1 method calls. – Haney May 19 '14 at 20:13