2009-09-01 71 views
0

我的WCF服務使用自定義憑證驗證器進行自定義基於消息的安全性,因爲我想確保每個調用我的Web服務的客戶端操作在我的數據庫中都有對應的用戶名和密碼。從WCF操作中獲取ClientCredentials

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的實現,使基於上下文的呼叫。

<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 

我不能依靠被調用者的誠信指定其實際用戶名,使不還傳遞一個密碼無法通過。我想避免每次打電話到我的Web服務都必須接受ClientCredentials。

謝謝。

回答

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