如何在WebAPI上保护控制器以仅供本地计算机使用

Luk*_*uke 12 c# security certificate asp.net-web-api

我有一个ASP.NET MVC网站,它使用了WebAPI,SignalR.

我希望我的服务器(托管网站的服务器)向WebAPI控制器发出HTTP请求 - 我希望这样做,以便我可以挂钩到我的网站的SignalR功能.

我想这样做,以便网站用户无法访问WebAPI控制器上的方法,但服务器可以.

我已经查看了一般保护WebAPI请求的选项,看起来我可以使用以下选项:

  • 通过每个请求发送用户名和密码AKA基本身份验证
  • 生成"客户端证书"并随每个请求发送

这些只是听起来像它们可以使用的两种方法,但我想知道如果请求来自localhost(同一服务器),使用这些方法是否过度.

是否过度,是否有更简单的方法来限制从本地计算机到WebAPI控制器的HTTP请求?

Dav*_*d L 18

如果您只想接受来自同一台计算机的请求,则可以检查IsLocal请求上下文MSDN的属性.

HttpRequest.Context.Request.IsLocal
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其构建为自定义授权属性并在全局中注册它,从而对所有Web API控制器强制执行要求.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Luk*_*uke 8

我想澄清一下是否HttpRequest.Context.Request.IsLocal安全.

我只是从中转换IsLocal()而来HttpWorkerRequest,它显示了以下代码:

internal bool IsLocal()
{
    string remoteAddress = this.GetRemoteAddress();
    if (string.IsNullOrEmpty(remoteAddress))
    {
        return false;
    }
    if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
    {
        return true;
    }
    if (remoteAddress == this.GetLocalAddress())
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

前两个检查看起来很好,但我很怀疑并且想要查看this.GetLocalAddress()返回要检查的内容.

在实例中System.Web.Hosting.IIS7WorkerRequest,这反编译为以下内容:

public override string GetLocalAddress()
{
    return this.GetServerVariable("LOCAL_ADDR");
}
Run Code Online (Sandbox Code Playgroud)

在我的本地环境中,这返回127.0.0.1,所以看起来都很好!

另外,根据这篇文章,localhost不能被欺骗.

  • 跟进此事的出色工作 (2认同)