一个简单的基于SOAP headers的WebService式身份验证 【翻译】
这篇文章是在我最近研究webservice的应用编程时所看到,虽然在原理上它是一篇比较初级技术文章,但从应用上基于此原理可以开发出实际的应用程序。
注: 链接到原文章
示例代码下载
介绍
最经我开发了为我的客户端返回一些敏感数据的 webservice 方法,我需要找到一个简单的方法来验证调用这些webservice方法的用户身份。这就是我要谈到的方法。
背景
我一直在开发 webservice 方法为我正在开发的客户端。在大多数情况下,他们传递的信息都是适应于任何公共的对象的,但最近我正在开发的一个项目要求我必须采取另一种的验证方法。
代码
我想让它在客户端容易实现,如下所示
1
protected System.Web.UI.WebControls.DataGrid dgData;
2
3
private void Page_Load(object sender, System.EventArgs e)
4
{
5
//simple client
6
AuthWebService.WebService webService = new AuthWebService.WebService();
7
AuthWebService.AuthHeader authentication = new
8
AuthWebService.AuthHeader();
9
10
authentication.Username = "test";
11
authentication.Password = "test";
12
webService.AuthHeaderValue = authentication;
13
14
//Bind the results - do something here
15
DataSet dsData = webService.SensitiveData();
16
17
dgData.DataSource = dsData;
18
dgData.DataBind();
19
20
}

2

3

4


5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

基本上所有应用客户端所要做的只是需要创建一个验证对象实例(此处即为下面要要定义的soap header 和 webservice类),填充用户名称和密码,然后传递此验证对象给webservice项目中。webservice代码也非常的简单,.NET framwork让你能轻松的创建一个自定义继承于
SoapHeader
类的SOAP头,在此自定义类中我们添加了新的用户名和密码成员属性1
<PRE lang=cs>using System.Web.Services.Protocols;
2
3
public class AuthHeader : SoapHeader
4
{
5
public string Username;
6
public string Password;
7
}</PRE>

2

3

4

5

6

7

下一步是添加自定义的验证对象到webservice方法中,在次示例中我包含一个webmethod方法
SensitiveData
,我了增加我们自定义的新的SOAP头,我们需要添加如下属性到方法中
完整的方法定义如下



































1
<?xml version="1.0" encoding="utf-8"?>
2
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
3
<soap:Header>
4
<AUTHHEADER xmlns="http://tempuri.org/">
5
<USERNAME>string</USERNAME>
6
<PASSWORD>string</PASSWORD>
7
</AUTHHEADER>
8
</soap:Header>
9
<soap:Body>
10
<SENSITIVEDATA xmlns="http://tempuri.org/" />
11
</soap:Body>
12
</soap:Envelope>
在实例代码中有相应的client 和 service 源代码

2

3

4

5

6

7

8

9

10

11

12
