如何保护WebAPI上的控制器以供仅本地计算机使用 [英] How to secure a controller on WebAPI for use by only the local machine

查看:90
本文介绍了如何保护WebAPI上的控制器以供仅本地计算机使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用WebAPI和SignalR的ASP.NET MVC网站。



我希望我的服务器(托管该网站的同一服务器)能够对WebAPI控制器的HTTP请求-我希望这样做,以便可以连接到我网站的SignalR功能。



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



我已经查看了一般用于保护WebAPI请求的选项,并且看来我有以下可用选项给我:




  • 为每个请求发送用户名和密码AKA基本认证

  • 生成一个客户证书,并随每个请求发送该证书。



这是听起来可行的仅有的两种方法,但我想知道是否如果请求将要从本地主机(同一台服务器)发出,则使用这些方法会产生过大杀伤力。



是否太过杀伤力了?

解决方案

如果只希望接受源自以下位置的请求,则更简单的方法来将HTTP请求从本地计算机限制为WebAPI控制器?

解决方案

在同一台计算机上,您可以检查请求上下文IsLocal 属性。 web.httprequest.islocal%28v = vs.110%29.aspx rel = noreferrer> MSDN 。

  HttpRequest.Context.Request.IsLocal 

然后可以将其构建到自定义授权属性中并注册

 公共静态类WebApiConfig 
{
public static void Register(HttpConfiguration config)
{
//其他Web API配置代码在这里

//这是全局注册的属性
config.Filters .Add(新的LocalRequestOnlyAttribute());
}
}

公共类LocalRequestOnlyAttribute:AuthorizeAttribute
{
受保护的覆盖布尔值IsAuthorized(HttpActionContext context)
{
return context.RequestContext.IsLocal;
}
}


I have an ASP.NET MVC website that makes use of WebAPI, 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.

I want to make it so that the websites users can't access the methods on the WebAPI controller, but the server can.

I have looked at the options for securing WebAPI requests generally and it seems like I have the following options available to me:

  • Send a username and password over each request AKA Basic Authentication
  • Generate a "Client Certificate" and send that with each request

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).

Is it overkill, is there an easier way to restrict HTTP requests from the local machine to a WebAPI controller?

解决方案

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

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上的控制器以供仅本地计算机使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆