Custom Authentication and Authorization with Soap Headers
Windows authentication works well for intranet scenarios, in which
you are authenticating against a user in your own domain. On the
Internet, however, you probably want to perform custom authentication
and authorization, perhaps against a SQL database. In that
case, you should pass custom credentials (such as the username and password) to your service and let it handle the authentication and authorization itself.
A convenient way to pass extra information along with a request to a XML Web service is a SOAP header. To do this, define a class that derives from SOAPHeader in your service, and then declare a public field of your service
as that type. This is exposed in the public contract for your
service, and made available to the client when the proxy is created
from WebServiceUtil.exe, as in the following example:
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
VB
Each WebMethod in your service can define a set of associated headers using the SoapHeader custom attribute.
By default, the header is required, but it is possible to define
optional headers as well. The SoapHeader attribute specifies
the name of a public field or property of the Client or Server class (referred to as a
Headers property in this topic). WebServices sets
the value of a Headers property before the method is called
for input headers, and retrieves the value when the method returns
for output headers. For more information about output or optional
headers see the .NET Framework SDK documentation.
<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
VB
A client then sets the header on the proxy class directly before making a method call that requires it, as shown in the following example:
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()
VB
To see this code in action, run the following sample:
- Securing your XML Web services on the server using Windows authentication follows exactly the same model as described for .aspx page.
- You can also programmatically set Windows credentials using the
Username and Password properties on the WebService proxy class.
- Lastly, you can do custom authentication by passing credential
information as SOAPHeaders, along with a SOAP request to the method
that requires it.
Copyright 2001 Microsoft Corporation. All rights reserved.