问题描述
我有一个使用 WebAPI、SignalR 的 ASP.NET MVC 网站.
I have an ASP.NET MVC website that makes use of WebAPI, SignalR.
我希望我的服务器(托管网站的同一台服务器)向 WebAPI 控制器发出 HTTP 请求 - 我希望这样做以便我可以连接到我网站的 SignalR 功能.
I wish for my server (the same server that hosts the website) to make HTTP requests to a WebAPI controller - I wish to do this so that I can hook into my website's SignalR functionality.
我想让网站用户无法访问 WebAPI 控制器上的方法,但服务器可以.
I want to make it so that the websites users can't access the methods on the WebAPI controller, but the server can.
我已经查看了一般用于保护 WebAPI 请求的选项,似乎我可以使用以下选项:
I have looked at the options for securing WebAPI requests generally and it seems like I have the following options available to me:
- 在每个请求 AKA 基本身份验证中发送用户名和密码
- 生成客户端证书"并随每个请求一起发送
这是仅有的两种听起来可行的方法,但我想知道如果请求来自本地主机(同一台服务器),使用这些方法是否有点过头了.
These are the only two methods that sound like they would work, but I wonder if it's overkill to use these methods if the requests are going to originate from localhost (the same server).
是否有点矫枉过正,有没有更简单的方法来限制从本地机器到 WebAPI 控制器的 HTTP 请求?
Is it overkill, is there an easier way to restrict HTTP requests from the local machine to a WebAPI controller?
推荐答案
如果你只想接受来自同一台机器的请求,你可以检查请求上下文的 IsLocal
属性 MSDN.
If you ONLY wanted to accept requests that originated from the same machine, you could check the IsLocal
property of the request context MSDN.
HttpRequest.Context.Request.IsLocal
然后您可以将其构建到自定义授权属性中并在全局范围内注册它,从而在您的所有 Web API 控制器上强制执行此要求.
You could then build it into a custom authorize attribute and register it globally, enforcing the requirement on all of your Web API controllers.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Other Web API configuration code goes here
// This is a globally registered attribute
config.Filters.Add(new LocalRequestOnlyAttribute());
}
}
public class LocalRequestOnlyAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext context)
{
return context.RequestContext.IsLocal;
}
}
这篇关于如何保护 WebAPI 上的控制器仅由本地计算机使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!