Pass username and password in xml request to wcf service for authentication?

I have a wcf service in which a user needs to authenticate before they can make a service call. There will be no website where the user will be verified using the login or Windows application / console where the user will be verified. I was thinking of doing something like this:

Submit a request:

<GetCars>
    <Credentials username="test" password="test" />
</GetCars>

If the username and password are successful, return a successful response for GetCars else.

The problem is that I don’t know how to transfer the request to the wcf service as above, and then read the username and password attributes for confirmation.

+3
source share
1 answer

, WCF . WCF SOAP WS-Security (.. wsHttpBinding, ). web.config :

<bindings>
  <wsHttpBinding>
    <binding name="myBindingName">
      <security mode="Message">
        <transport clientCredentialType="None" />
        <message clientCredentialType="UserName" />
      </security>

:

<behaviors>
  <serviceBehaviors>
    <behavior name="myBehaviorName">
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="NameSpaceName.Class,AssemblyName" />
      </serviceCredentials>

, , UserNamePasswordValidator ( System.IdentityModel.dll System.IdentityModel.Selectors) Validate:

public class MyValidator : UserNamePasswordValidator {
    public override void Validate(string userName, string password) {
        // check password. if success, do nothing
        // if fail, throw a FaultException
    }
}

ASP.Net WCF ClientCredential , :

// This pattern needs to be repeated and username / password set with every creation
// of a client object.  This can be refactored to a separate method to simplify.
MyAPIClient client = new MyAPIClient();

// yes UserName is there twice on purpose, that the proper structure
client.ClientCredentials.UserName.UserName = theUsername;
client.ClientCredentials.UserName.Password = thePassword;

try {
    client.Open();
    client.DoSomething();
    client.Close();
} catch (Exception ex) {
    // handle exception, which should contain a FaultException;
    // could be failed login, or problem in DoSomething
}

, , , behaviorConfiguration bindingConfiguration.

+6

All Articles