blubberbo
blubberbo

Reputation: 4613

mvc web api only allow requests from same server

I am building an mvc application and I am making an api controller to allow ajax requests from some of my front end pages. I want to restrict the api controller actions to only allow requests from my server (so people can not call my api from their own sites).

After some searching around, I found numerous solutions proposing a custom authorize attribute, which I made:

public class LocalRequestOnlyAttribute : AuthorizeAttribute
    {
     protected override bool AuthorizeCore(HttpContextBase context)
            {
                return context.Request.IsLocal;
            }
}

and then dropped it on my controller action with [LocalRequestOnly]

it works fine on localhost, but on my aws server, it does not work, the ajax request comes back as an error

EDIT - Details:

I am using the hostname with a relative path. so my url for the ajax call is "/api/getdata". I am not setting any ajax request headers. The error I am getting back is No 'Access-Control-Allow-Origin' header is present on the requested resource.

Upvotes: 2

Views: 2602

Answers (3)

Jay Shah
Jay Shah

Reputation: 3771

You cannot Prevent it because Http is stateless and only way to check that request is ajax or coming from your server or site - is using Http headers, but these headers are not trustworthy as they can be set manually by server side coding.

However, it can be made difficult by disabling CORS and checking these Http headers like Referer (Contains address of the webpage from where ajax request is made), User-Agent and X-Requested-With (set to XMLHttpRequest for ajax requests).

Upvotes: 0

Kim Hoang
Kim Hoang

Reputation: 1368

You don't need to do anything. By default, Web API only allow the request from same domain, CORS is not supported.

Upvotes: 1

murtuza
murtuza

Reputation: 1169

I don't know how to fix the problem, but your solution is not working because IsLocal does not do what you expect. Here's the documentation for it: https://msdn.microsoft.com/en-us/library/system.web.httprequest.islocal(v=vs.110).aspx

IsLocal checks whether the client and the server are on the same computer. So this would work if you were browsing in chrome on your amazon server. What you are looking to do is prevent Cross-Origin requests.

Upvotes: 1

Related Questions