https – How to Allow Requests Only for Specific Referer Within Domain

corshttphttp-headershttps

please consider following scenario:

I have an API running on the same server as IIS. IIS is hosting a webpage.
I want to allow access to the API to this webpage only. No other page from within the domain.

Let's say the domain is example.com and the webpage is example.com/page
Any of these should not work, example.com, example.com/other. Only example.com/page should have access.

As bonus, I would like to know if I can block direct access to the API. So I want to forbid to go to the URL bar and make a get requests with the API address.

Best Answer

I want to allow access to the API to this webpage only. No other page from within the domain.

What you're describing is best implemented as an HTTP Referer [sic] whitelist on the api side. Http Referer header describes the referring site, and the browser will ad it by default - but be aware that the header is client supplied, so while this will stop naive web users from hitting your API from different sites, if the user themself is motivated to reach the api from a site, they can forge a http Referer header trivially.

The only real way to protect an API from illegitimate usage is to provide authentication and authorization to the API server. Even then, anyone authorized cna provide the same credentials in an api call with a forged http header. So at the end of the day, you can't really stop a motivated party from accessing the api without using the site. Websites today don't typically worry about this, though - they focus on making sure they use CORS to protect against cross site scripting attacks on unknowing users, and focus on authentication and authorization to block bad actors, who will simply forge anything client supplied.

As bonus, I would like to know if I can block direct access to the API. So I want to forbid to go to the URL bar and make a get requests with the API address.

Whitelisting certain referrers should make that work. A link typed directly into the URL doesn't provide a referer so that wouldn't match your whitelist. You're not really blocking access to the api, which needs to be accessible from the arbitrary IPs of legitimate users of your site, but you are doing a simple authorization check by checking referer and rejecting requests which don't meet your whitelist.

Related Topic