我通过Azure Api管理门户公开了Web Api,并且我已经使用共享密钥向SET HTTP标头添加了一个策略。这样我想阻止访问我的api后端(api托管在azure web app上)。现在我想知道我应该在我的webapi中添加自定义逻辑以检查共享密钥?应该是actionFilters吗?
答案 0 :(得分:0)
最简单的地方是使用消息处理程序。看起来应该是这样......
public class RestrictClientHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
IEnumerable<string> secrets = null;
request.Headers.TryGetValues("myapi-secret",out secrets);
var secret = secrets.FirstOrDefault();
if (secret == null || secret != "the secret" )
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden) { RequestMessage = request, Content=new StringContent("Direct access to this API is not allowed")});
}
return base.SendAsync(request, cancellationToken);
}
}
然后通过将其添加到挂起配置对象的MessageHandlers集合来安装它。