Reputation: 6285
what is the best way to limit access to a webapi 2 controller within a MVC project to only the hosted App Service?
I have created a endpoint which my MVC client is accessing. The entire application is published to azure through an app service. How can I now protect the endpoint from being called outside of the application context?
Upvotes: 0
Views: 2478
Reputation: 4633
Based on your comments you should consider restructuring your solution.
Having a dedicated authorization server clearly separates out the identity responsibility allowing you to control access for other future clients and possibly restrict access to only certain endpoints (aka scopes).
Upvotes: 1
Reputation: 6965
You could use an API key in the request's header to filter out unwanted request. 1. Implement a customer authorization attribute (AuthorizationFilter) class.
[HttpPost, AuthorizationFilter]
public CustomerInfo GetCustomerInfo(CustomerInfoRequest request)
{
return Business.GetCustomerInfo(request);
}
2. In your controller class
public override void OnAuthorization(HttpActionContext ctx)
{
if (!VerifyHeaders(ctx))
{
ctx.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
return;
}
base.OnAuthorization(ctx);
}
private bool VerifyHeaders(HttpActionContext ctx)
{
IEnumerable<string> values = new List<string>();
//Read the API key from the request header
ctx.Request.Headers.TryGetValues("ApiKey", out values);
var apiKey = values?.FirstOrDefault();
return CheckApiKey(apiKey);
}
private bool CheckApiKey(string apiKey)
{
//Verification is done here
return true;
}
Upvotes: 0