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?
Based on your comments you should consider restructuring your solution.
For authentication I would consider implementing an authorization server (again in an independent project) that issues tokens to the client (in your case the MVC app) and the client would then access the API using this token. For implementing an auth server you have a couple of options
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).
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.