I have a MVC Controller which exposes a Initialise Action
. The other virtual web application hosted on same IIS will need to access this Action.
For security reason, only request coming from same web server (where MVC app is hosted) will need to be granted access to this Iniliase method.
Could someone please help how to achieve this? We can't use localhost to validate as this application will be hosted in Azure which doesn't support locahost requests.
To restrict the public action method in MVC, we can use the “NonAction” attribute. The “NonAction” attribute exists in the “System. Web.
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.
Answer is "Pipeline"
My answer is regarding restricting server-side requests.
The website that calls Initialise
would need to make a request to http://www.example.com/controller/Initialise
rather than http://localhost/controller/Initialise
(replacing www.example.com
and controller
with your domain and controller names of course).
HttpRequest.IsLocal should be checked in your controller action:
if (!Request.IsLocal)
{
throw new SecurityException();
}
This will reject any requests not coming from the local host. This approach assumes that both the calling site and the requested site share the same IP address - the documentation states that this should work:
The IsLocal property returns true if the IP address of the request originator is 127.0.0.1 or if the IP address of the request is the same as the server's IP address.
For restricting client-side requests Google "csrf mitigation".
If your server has multiple ip addresses, you'll need some extra code. The following handles multiple ip addresses, and handles CDN like cloudflare which will have the wrong ip address in the Request.UserHostAddress property.
Code:
private bool IsLocal()
{
if (Request.IsLocal)
{
return true;
}
string forwardIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
{
string ipString = addr.Address.ToString();
if (Request.UserHostAddress == ipString || forwardIP == ipString)
{
return true;
}
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With