从WCF操作中获取ClientCredentials

时间:2009-09-01 21:36:50

标签: wcf wcf-security wcf-extensions

我的WCF服务使用自定义凭据验证程序来实现基于消息的自定义安全性,因为我想确保在我的Web服务上调用操作的每个客户端在我的数据库中都有相应的用户名和密码。

Imports System.IdentityModel.Selectors
Imports System.IdentityModel.Tokens

Public Class CredentialsValidator
    Inherits UserNamePasswordValidator

    Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
        Dim authenticationApi As New AuthenticationGateway()
        If Not authenticationApi.IsValid(userName, password) Then
            Throw New SecurityTokenException("Validation Failed.")
        End If
    End Sub
End Class

事情是,一旦用户通过身份验证,我想在我的OperationContract实现中使用userName来进行基于上下文的调用。

<ServiceContract(Name:="IMyService")> _
Public Interface IMyService
    <OperationContract()> _
    Function GetAccountNumber() As String
End Interface

Public Class IntegrationService
    Implements IIntegrationService

    Public Function GetAccountNumber() As String Implements IMyService.GetAccountNumber
        Dim userName As String '' Here I want the userName set from credentials
        Dim accountApi As New AccountGateway()
        Return accountApi.GetAccountNumber(userName)
    End Function
End Class

我不能依赖于被调用者的诚实来指定他们的实际userName,所以如果不传递密码就不能传递它。我希望避免每次调用我的Web服务都必须接受ClientCredentials。

感谢。

1 个答案:

答案 0 :(得分:1)

Public Class IntegrationService
    Implements IIntegrationService

    Private ReadOnly Property UserName As String
        Get
            Return ServiceSecurityContext.Current.PrimaryIdentity.Name
        End Get
    End Property

    Public Function GetAccountNumber() As String Implements IMyService.GetAccountNumber
        Dim accountApi As New AccountGateway()
        Return accountApi.GetAccountNumber(UserName)
    End Function
End Class