wcfwcf-securitywcf-extensions

Obtaining ClientCredentials from WCF operation


My WCF Service uses a custom credentials validator for custom Message-based security, because I want to ensure each client calling an operation on my web service has a corresponding username and password in my database.

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

Thing is, once the user passes authentication I want to use the userName in my OperationContract implementations to make context based calls.

<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

I cant rely on the honesty of the callees to specify their actual userName so can't pass it without also passing in a password. I wanted to avoid having every single call to my web service having to accept the ClientCredentials.

Thanks.


Solution

  • 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