Windows 身份验证非常适合 Intranet 方案,这种情况下您是对自己的域中的用户进行身份验证。然而在 Internet 上,您可能需要对 SQL 数据库执行自定义身份验证和授权。在这种情况中,应向服务传递自定义凭据(如用户名和密码),并让服务自己处理身份验证和授权。
将额外的信息连同请求一起传递给 XML Web 服务的简便方法是通过 SOAP 标头。为此,需要在服务中定义一个从 SOAPHeader 派生的类,然后将服务的公共字段声明为该类型。这在服务的公共合同中公开,并且当从 WebServiceUtil.exe 创建代理时可由客户端使用,如下例所示:
using System.Web.Services;
using System.Web.Services.Protocols;
// AuthHeader class extends from SoapHeader
public class AuthHeader : SoapHeader {
public string Username;
public string Password;
}
public class HeaderService : WebService {
public AuthHeader sHeader;
...
}
Imports System.Web.Services
Imports System.Web.Services.Protocols
' AuthHeader class extends from SoapHeader
Public Class AuthHeader : Inherits SoapHeader
Public Username As String
Public Password As String
End Class
Public Class HeaderService : Inherits WebService
Public sHeader As AuthHeader
...
End Class
import System.Web.Services;
import System.Web.Services.Protocols;
// AuthHeader class extends from SoapHeader
public class AuthHeader extends SoapHeader {
public var Username:String;
public var Password:String;
}
public class HeaderService extends WebService {
public var sHeader:AuthHeader;
...
}
|
C# | | | |
服务中的每个 WebMethod 都可以使用 SoapHeader 自定义属性定义一组关联的标头。默认情况下,标头是必需的,但也可以定义可选标头。SoapHeader 属性指定公共字段的名称或者 Client 或 Server 类的属性(本标题中称为 Headers 属性)。在为输入标头调用方法前,WebService 设置 Headers 属性的值;而当方法为输出标头返回时,WebService 检索该值。有关输出标头或可选标头的更多信息,请参阅 .NET 框架 SDK 文档。
[WebMethod(Description="This method requires a custom soap header set by the caller")]
[SoapHeader("sHeader")]
public string SecureMethod() {
if (sHeader == null)
return "ERROR: Please supply credentials";
else
return "USER: " + sHeader.Username;
}
<WebMethod(), SoapHeader("sHeader")> Public Function SecureMethod() As String
If (sHeader Is Nothing)
Return "ERROR: Please supply credentials"
Else
Return "USER: " & sHeader.Username
End If
End Function
WebMethodAttribute(Description="This method requires a custom soap header set by the caller")
SoapHeaderAttribute("sHeader")
public string SecureMethod() {
if (sHeader == null)
return "ERROR: Please supply credentials";
else
return "USER: " + sHeader.Username;
}
|
C# | | | |
然后,客户端在调用要求标头的方法之前,直接在代理类上设置标头,如下面的示例所示:
HeaderService h = new HeaderService();
AuthHeader myHeader = new AuthHeader();
myHeader.Username = "JohnDoe";
myHeader.Password = "password";
h.AuthHeader = myHeader;
String result = h.SecureMethod();
Dim h As New HeaderService
Dim myHeader As New AuthHeader
myHeader.Username = "JohnDoe"
myHeader.Password = "password"
h.AuthHeader = myHeader
Dim result As String = h.SecureMethod()
var h:HeaderService = new HeaderService();
var myHeader:AuthHeader = new AuthHeader();
myHeader.Username = "JohnDoe";
myHeader.Password = "password";
h.AuthHeader = myHeader;
var result:String = h.SecureMethod();
|
C# |