2

If I have a Web API Controller in my MVC application and I am calling a GET request to it via jQuery $ajax, how can I validate the call to make sure it is coming from my application?

Is it something where I need to check the IP it is coming from? Can I use the AntiForgeryToken?

I basically want the API Controller to only allow requests from my application, not from someone else who just knows the endpoint. I don't want people to be able to replicate the API calls.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
blubberbo
  • 4,441
  • 4
  • 23
  • 36
  • 2
    Did you read about "Same Origin Policy" ? – Shyju Dec 11 '16 at 18:11
  • I have read a little. It sounds like what I want to use is the antiforgerytoken, but I don't quite understand why someone else cannot just replicate that – blubberbo Dec 11 '16 at 18:15
  • Might want to look into using JWT or some other token-based validation system. See also http://stackoverflow.com/q/11476883/215552 – Heretic Monkey Feb 02 '17 at 22:52

1 Answers1

2

You can use CORS to restrict calls from other origins. Along with CORS you should also secure api using authentication (to prevent unauthenticated access).

To disable request from different origin, you can use [DisableCors] attribute on you web api (web api 2) Example below. By default CORS are disabled. You should use this attibute if it is enabled at higher level (ex-controller) and you want to restrict at lower level (ex- action)

[DisableCors]
public class UsersController : ApiController
{
    public HttpResponseMessage GetUser(int id) { ... }
}

To enable access to this controller from http://contoso.com

[EnableCors(origins: "http://www.contoso.com", headers: "*", methods: "*")]    
public class UsersController : ApiController
{
   public HttpResponseMessage GetUser(int id) { ... }
}
Kaushal
  • 1,251
  • 1
  • 8
  • 8
  • 1
    What's the different between doing [DisableCors] and using the anti forgery token? – blubberbo Feb 02 '17 at 23:04
  • 1
    CORS and anti forgery are different concepts. CORS restricts the domain which can access your api. Anti forgery tokens are generated by server, sent to client via cookie and hidden field, to validate form post is from trusted source. Will anti forgery suffice, depend on architecture of your application. If you using MVC based application where response is html page with form, anti forgery is very useful. If you using web api, anti forgery is not available. Also if you expect api to accept request from set of domains (or different domain) , then use CORS to restrict domain. – Kaushal Feb 04 '17 at 22:47