更新:2007 年 11 月
本主题演示在使用 Windows Communication Foundation (WCF) 调用 ASP.NET 身份验证服务时,如何验证自定义凭据以对用户进行身份验证。通常情况下,身份验证只需要用户名和密码。但在某些情况下,可能还需要使用其他凭据(例如标识号)来验证用户的标识。
若要使用户从可以发送和使用 SOAP 1.1 消息的客户端应用程序(例如 Java 应用程序)登录,请使用身份验证服务的 WCF 实现。
验证自定义凭据以进行身份验证
在 Web 应用程序的 Global.asax 文件中,为 Authenticating 事件创建事件处理程序。
在此处理程序中,读取处理程序的 AuthenticatingEventArgs 参数的 CustomCredential 属性内容,然后验证值。
下面的示例演示如何从 CustomCredential 属性中读取两个身份验证值,然后将它们传递给名为 StudentAuthentication 的自定义身份验证类。
Sub AuthenticationService_Authenticating _ (ByVal sender As Object, _ ByVal e As System.Web.ApplicationServices.AuthenticatingEventArgs) Dim studentid As String = String.Empty Dim answer As String = String.Empty Dim credentials As String() = _ e.CustomCredential.Split(New Char() {","c}) If (credentials.Length > 0) Then studentid = credentials(0) If (credentials.Length > 1) Then answer = credentials(1) End If End If Try e.Authenticated = _ StudentAuthentication.ValidateStudentCredentials _ (e.Username, e.Password, studentid, answer) Catch ex As ArgumentNullException e.Authenticated = False End Try e.AuthenticationIsComplete = True End Subvoid AuthenticationService_Authenticating(object sender, System.Web.ApplicationServices.AuthenticatingEventArgs e) { string studentid = String.Empty; string answer = String.Empty; string[] credentials = e.CustomCredential.Split(new char[] { ',' }); if (credentials.Length > 0) { studentid = credentials[0]; if (credentials.Length > 1) { answer = credentials[1]; } } try { e.Authenticated = StudentAuthentication.ValidateStudentCredentials (e.UserName, e.Password, studentid, answer); } catch (ArgumentNullException ex) { e.Authenticated = false; } e.AuthenticationIsComplete = true; }在 Global.asax 文件的 Application_Start 方法中,绑定 Authenticating 事件的事件处理程序。
下面的示例演示如何将一个处理程序绑定到 Authenticating 事件。
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) AddHandler System.Web.ApplicationServices.AuthenticationService.Authenticating, _ AddressOf Me.AuthenticationService_Authenticating End Subvoid Application_Start(object sender, EventArgs e) { System.Web.ApplicationServices.AuthenticationService.Authenticating += new EventHandler<System.Web.ApplicationServices.AuthenticatingEventArgs>(AuthenticationService_Authenticating); }从可以使用 Web 服务的 SOAP 消息的应用程序中调用身份验证服务,并在 CustomCredential 属性中传递要进行身份验证的其他值。
编译代码
- 必须在 Web 服务器上设置身份验证服务才能让前面的示例工作。有关更多信息,请参见如何:启用 WCF 身份验证服务。
可靠编程
上面的代码示例演示一个自定义身份验证类,如果任一参数为 null,则该类将引发 ArgumentNullException。您的代码必须处理验证期间引发的任何异常。
安全性
始终通过使用安全套接字层 (SSL)、HTTPS 协议来访问身份验证服务。
请参见
概念
Windows Communication Foundation 身份验证服务概述