2

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.

2
  • do you have more info? are you using the ip or the hostname to connect? what do the AJAX request headers look like? what's the error that comes back? Commented Dec 14, 2016 at 5:07
  • specifics added Commented Dec 14, 2016 at 5:17

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

@blubberbo, I am not sure about postman, never use it before. Can you simply create a simple html page with jquery, try to use jQuery.ajax to call to your web api inside that page. I believe you cannot access that api.
0

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).

Comments

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.