Access WCF client credentials from a service

I have the following WCF service call (using basic authentication):

client.ClientCredentials.UserName.UserName = "username"; client.ClientCredentials.UserName.Password = "password"; client.MyServiceFunction(); 

On the server, I have:

 class MyService : IMyService { string MyServiceFunction() { return GetUsernameHere(); } } 

My question is: can I access these credentials in the WCF service, and if so, how? That is, how would I implement the GetUsernameHere function?

+7
c # wcf basic-authentication
source share
1 answer

For this type of verification to work, you must write your own validator for the username and password.

You create a class that inherits from UserNamePasswordValidator , and specify it in your webconfig as follows:

  <serviceBehaviors> <behavior name="CustomValidator"> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType= "SomeAssembly.MyCustomUserNameValidator, SomeAssembly"/> </serviceCredentials> </behavior> </serviceBehaviors> 

The custom validation class will look like this:

 public class MyCustomUserNameValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { // Do your username and password check here } } 

The password is not accessible outside the WCF validation part, so you can only get it using a custom validator.

However, if you just want a username, it should be accessible via:

OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name

however, you may need to specify <message establishSecurityContext="true" /> as part of your binding security, and this is not available for all bindings, for example. BasicHttpBinding

 <bindings> <wsHttpBinding> <!-- username binding --> <binding name="Binding"> <security mode="Message"> <message clientCredentialType="UserName" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings> 
+7
source share

All Articles