How to make .NET Web Api private for only my application

I created a new Web Api MVC4 project and built a RESTful API with API Controllers, then I use regular MVC controllers to render views using HMTL5 / KnockoutJS / JS.

The views interact with the application via the REST Api as such (the baseUrl property points to the correct REST endpoint for my given entity):

        this.Post = function (entity) {

            return $.ajax(baseUrl, {
                type: 'post',
                data: ko.toJSON(entity),
                contentType: 'application/json',
                dataType: 'json'
            });
        };

      

Now, how can I make it so that ONLY my application can consume (or view) my RESTful API?

+3


source to share


2 answers


The best way to handle making something private for your application is to always handle it at the network level. Don't even expose the Web API to the outside world. Place it behind the DMZ and put a hole through the firewall specifically for your user-centric application. Then nothing else can touch him.

EDIT

Sorry, I wasn't paying attention to the fact that you are accessing it via AJAX, so I suggested not technically working. However, there is another merit in this approach if you only need client access for multiple endpoints. You can set up actions in your application that simply proxies the request to the private API endpoints, and then invokes actions for your user-centric application for AJAX, not directly for the web API.



However, if everything needs to be client-side accessible, you must expose the web API. Authentication is your only option at this point, but securing that client-side is nearly impossible (you would need to store an authentication token or methodology for client-side authentication, and also allow anyone who wants to look in your code to mimic that you did it).

In general, if the code is public (available without authentication), then you want to show non-atomic endpoints (GET requests and other things that don't actually make any changes to any data). Once the user has authenticated with your user-centric application, you can then expose endpoints that are atomic but should only be limited to have change access. You should also use your credentials to authenticate with your web API and not with any global set of credentials for your application. This way, you can control your access at the web API level and reject change requests that they shouldn't have access to. Anything more globalshould only go through your web app, proxying to a truly private web API as described in my answer.

+5


source


Yes, you can!



Use a message handler or OWIn middleware to validate the request url if they are from your domain, then allow the call to pass. Otherwise, ignore it.

+1


source







All Articles