简体   繁体   中英

Accessing WCF client credentials from the service

I have the following call to a WCF service (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?

For this type of validation 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 like this:

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

The custom validator 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 available outside of the validation portion of WCF so you can only retrieve it using the custom validator.

However if you just want the 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's security, and this isn't available on all bindings eg. basicHttpBinding

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM