使用自定义 SOAP 标头验证 .NET Web 服务






4.32/5 (27投票s)
如何使用自定义 SOAP 标头验证 .NET Web 服务
引言
我们中的许多人都希望保护对我们 Web 服务的调用,对吧?
有很多方法可以做到这一点,其中一种是使用自定义 SOAP 标头。
使用这种方法,我们只需将必需的 SOAP 标头添加到我们的 Web 服务调用中。
我们将 SOAP 标头嵌入到我们的消息中,并在服务器上验证其内容。
如果 SOAP 标头验证成功完成,Web 服务器会将 Web 服务响应发送给消费者。
很简单,对吧?
Using the Code
现在让我们看看如何在 Visual Studio 中实现这一点
/// <summary>
/// Summary description for SOAPHeaderService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Name = "TestService",ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SOAPHeaderService : System.Web.Services.WebService
{
public SOAPHeaderService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
请注意,“WebService
”属性的“Binding
Name
”参数设置为“TestService
”,我稍后会解释这一点。
现在,我编写要包含在 SOAP 消息中的自定义 SOAP 标头。
为此,我将创建一个继承自“System.Web.Services.Protocols.SoapHeader
”的类,并将所需的属性放入其中。
public class UserCredentials : System.Web.Services.Protocols.SoapHeader
{
public string userName;
public string password;
}
让我们在我们的服务中添加该标头的实例
public class SOAPHeaderService : System.Web.Services.WebService
{
// Visual studio will append a "UserCredentialsValue" property to the proxy class
public UserCredentials consumer;
请注意,Visual Studio 将在 Web 服务代理中创建一个名为“UserCredentialsValue
”的属性,它将映射 Web 服务中的“consumer
” public
属性。
现在我们必须编写一个使用该标头进行消息传递的“Web 方法”。
[WebMethod]
[SoapDocumentMethod(Binding = "TestService")]
[SoapHeader("consumer",Required=true)]
public string GetBalance()
{
if (checkConsumer())
return consumer.userName + " had 10000000 credit";
else
return "Error in authentication";
}
private bool checkConsumer()
{
// In this method you can check the username and password
// with your database or something
// You could also encrypt the password for more security
if (consumer != null)
{
if (consumer.userName == "Ahmed" && consumer.password == "1234")
return true;
else
return false;
}
else
return false;
}
请注意,我已将我在声明服务时使用的“Binding
”值添加到该方法中。
我还声明了该方法在调用时将需要的 SOAP 标头,并将其声明为必需的。
现在,唯一剩下的事情就是使用 SOAP 标头调用该服务
SOAPHeaderService.SOAPHeaderService service = new SOAPHeaderService.SOAPHeaderService();
SOAPHeaderService.UserCredentials user = new SOAPHeaderService.UserCredentials();
user.userName = "Ahmed";
user.password = "1234";
service.UserCredentialsValue = user;
Console.WriteLine(service.GetBalance());
我们只需获取服务的引用和 SOAP 标头,分配 SOAP 标头属性,将其附加到 SOAP 消息,然后对 Web 方法进行调用。
这是调用服务后控制台的结果,用户名 = “Ahmed
” 且密码 = “1234
”

这是使用其他数据的结果

关注点
在开发过程中,许多开发人员忽略了保护他们的 Web 服务,他们认为这是一项困难而繁琐的任务。
事实上,保护 Web 服务完全在于理解消息传递层和协议,你只需要深入一点,就会发现它是一项非常简单的任务。
我将发布 ISA,介绍其他保护 Web 服务的方法。
历史
- 2008 年 6 月 30 日:初始发布