简体   繁体   English

如何以编程方式限制对 Web 服务的访问?

[英]How can I programatically limit access to a Webservice?

I am writing a traditional ASMX webservice using C# with.Net 2.0 for deployment on IIS.我正在使用带有.Net 2.0 的 C# 编写传统的 ASMX Web 服务,以便在 IIS 上进行部署。 The webservice will be deployed in a shared hosting environment where each client has their own copy of the application sitting in a separate virtual directory (I know, I know - it's a legacy app). Web 服务将部署在共享托管环境中,每个客户端都有自己的应用程序副本,位于单独的虚拟目录中(我知道,我知道 - 这是一个遗留应用程序)。 There will be an individual copy of the Webservice sitting in each virtual directory.每个虚拟目录中都会有一个单独的 Web 服务副本。

As the Webservice could potentially do some powerful things, I would like to optionally limit access to it to certain IP addresses.由于 Web 服务可能会做一些强大的事情,我想选择性地限制对某些 IP 地址的访问。 Doing this in the firewall isn't a very good option as it is only the webservice that should be limited and not the rest of the website - and it is on a per-virtual-directory level.在防火墙中执行此操作不是一个很好的选择,因为它只是应该限制的 web 服务,而不是网站的 rest - 它位于每个虚拟目录级别。

Can I programmatically read the IP address of the requestor and compare it to a list so I can reject calls from other addressess?我可以以编程方式读取请求者的 IP 地址并将其与列表进行比较,以便我可以拒绝来自其他地址的呼叫吗? Are there any major pitfalls to this?这有什么重大的陷阱吗?

Thanks谢谢

Yes you can do it easily.是的,你可以轻松做到。

[WebMethod]
public bool IsAlive()
{
     string callingAddress = HttpContext.Current.Request.UserHostAddress;
     return (callingAddress == allowedAddress);
}

The only pitfalls are the maintenance of the list of IP addresses.唯一的缺陷是维护 IP 地址列表。

It's also worth noting that you can configure IP address access control on a per web application basis from within IIS.还值得注意的是,您可以在 IIS 中基于每个 web 应用程序配置 IP 地址访问控制。 I have used both approaches at different times and it really just comes down to how you want to maintain the list of authorised IP addresses.我在不同的时间使用了这两种方法,这实际上归结为您希望如何维护授权的 IP 地址列表。

only pitfalls are the maintenance of the list of IP addresses.唯一的缺陷是维护 IP 地址列表。

It's also worth noting that you can configure IP address access control on a per web application basis from within IIS.还值得注意的是,您可以在 IIS 中基于每个 web 应用程序配置 IP 地址访问控制。 I have used both approaches at different times and it really just comes down to how you want to maintain the list of authorised IP addresses.我在不同的时间使用了这两种方法,这实际上归结为您希望如何维护授权的 IP 地址列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM