Vikash Sharma
Vikash Sharma

Reputation: 36

Find which host have requested by REST api using c#

I have hosted my REST api on Microsoft Azure abc.com and I wanted to receive calls only from xyz.com which is HTML based pages.

Is there any way I can find the REST request has been sent by xyz.com, or any other simple way to secure rest api for html based consumer?

using MVC, ASP.NET

Upvotes: 0

Views: 1147

Answers (2)

Sam_Butler
Sam_Butler

Reputation: 303

Irrespective of your backend being C#, you can use the Access-Control-Allow-Origin HTTP header to specify xyz.com as the permitted referrer.

You must specify the Vary: Origin header when Access-Control-Allow-Origin is anything other than a wildcard. This "indicate[s] to clients that server responses will differ based on the value of the Origin request header"

You can learn more about this header and how it works in different scenarios in this SO answer: https://stackoverflow.com/a/10636765/1449160

See also: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

This, however, is not sufficient security, as CORS is a client-implemented feature. You likely want your C# backend to check the referrer as one part of your access control. Here is another SO question whose answers deal with that issue: Getting the HTTP Referrer in ASP.NET

Finally, as far as securing your API against unauthorised access, there are many ways to do this that would be beyond the scope of a few paragraphs here. OAuth is probably the most well-known, but you can also generate a unique token for your client and include it in a header or use HTTP basic authentication with your token as either the username or password, etc.

Upvotes: 1

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

The simplest way is to inspect the HTTP request you're receiving and inspect the Referer header, as detailed in this question:

How do I get the referrer URL in an ASP.NET MVC action?

The problem is that it's not 100% secure, since the Referer header can be spoofed, if someone is determined to bypass it.

A different approach is to add IP-based filters which block incoming requests only for the IPs mapped to xyz.com, but this depends exactly how you're hosting your site - a VM on azure, hosted website or something else.

Upvotes: 0

Related Questions