Welcome to MSDN Blogs Sign in | Join | Help
WCF Authentication: Custom Username and Password Validator

There are a number of authentication techniques supported by WCF. For instance Windows Authentication, X509 Certificates, Issued Tokens, and Username and Password are all mechanisms that can be used for authentication.

These client credential types are configured as part of the binding configuration for an endpoint. For example the config section below customises the netTcpBinding to use an X509 certificate:

<netTcpBinding>

  <binding name="tcpWithMessageSecurity">

    <security mode="Message" >

      <message clientCredentialType="Certificate"/>

    </security>

  </binding>

</netTcpBinding>

If you change the Client Credential Type to “UserName”, you can then pass username and passwords to the service and authenticate the client based on these credentials.

Sending unencrypted username and password over any communication framework is usually not advisable. Therefore, when you opt in for the UserName client credential type, WCF insists that your service must also reference a service certificate that contains a private key. The public key in this certificate is used to protect the confidentiality of the username and password sent to the service. The private key is then used by the service to obtain those encrypted credentials.

If a server certificate is not specified, at service start-up time, you will receive the following exception: “The service certificate is not provided. Specify a service certificate in ServiceCredentials.”

By default, when a user name and password is used for authentication, WCF uses Windows to validate the username and password. Having said that, WCF is one of the world’s most extensible communication frameworks and it should not surprise you if I say that you can take control of the username and password validation:

This first step is to create a “validator” by inheriting from the UserNamePasswordValidator class and override the Validate method (Add a reference to System.IdentityModel.dll first):

public class CustomUserNameValidator : UserNamePasswordValidator

{

 public override void

  Validate(string userName, string password)

 {

  // perform the validation logic

 }

 

The next step is to configure the service to use this custom validator. As this is the local behavior of the service, you will need to specify the custom validator as part of your service behavior configuration:

<serviceBehaviors>

  <behavior name="CustomValidator">

    <serviceCredentials>

 

      <userNameAuthentication

        userNamePasswordValidationMode="Custom"

        customUserNamePasswordValidatorType=

           "MyAssembly.CustomUserNameValidator, MyAssembly"/>

 

      <serviceCertificate

        findValue="localhost"

        x509FindType="FindBySubjectName"

        storeLocation="CurrentUser"

        storeName="My" />

    </serviceCredentials>

  </behavior>

 

As you can see, there are two elements defined as part of the serviceCredentials section. The userNameAuthentication element specifies that a custom validator is used and the serviceCertificate element provides a reference to the X509 certificate used by the service to ensure the integrity of the client credentials. See here for information on how to create a temporary certificate for use during development.

Do not forget to set service’s behaviourConfiguration property to the name of the service behavior defined above:

<service name="..." behaviorConfiguration="CustomValidator">

Both client and service endpoints need to enable Username and Password authentication mode on their bindings:

<netTcpBinding>

  <binding name="tcpWithMessageSecurity">

    <security mode="Message" >

      <message clientCredentialType="UserName"/>

    </security>

  </binding>

</netTcpBinding>

Our service is now fully configured.  The final step is to provide the username and password to the client proxy which can then be encrypted and sent to the service. If you are using the ChannelFactory directly to create a proxy then use the code below to set the username and password programmatically:

ChannelFactory<ISimpleService> factory =

 new ChannelFactory<ISimpleService>(endpointConfigurationName);

factory.Credentials.UserName.UserName = "Pedram";

factory.Credentials.UserName.Password = "Password01";

However, if SvcUtil or Visual Studio has generated a proxy for you, use the code below to set the username and password:

proxy.ClientCredentials.UserName.UserName = "Pedram";

proxy.ClientCredentials.UserName.Password = "Password01";

 

Please note that there is no way to set the username and password in config.

Depending on the type of service certificate, you may need to specify a DNS identity for your client endpoints. This is used when the client authenticates the service to ensure that it is talking to the expected service and not any other hoax service intercepting your calls to the genuine service. The exception below is an indication of this:

Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was 'X' but the remote endpoint provided DNS claim 'Y'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'Y' as the Identity property of EndpointAddress when creating channel proxy.

You can modify the client endpoint to include an identity element such as the one below (see here for more information on service identity):

<identity>

  <dns value="pedramr"/>

</identity>

You are now ready to test the service.

You can also download a sample application which tries this technique over netTcp and wsHttp bindings from here (built using Visual Sudio 2008 beta 2 and is compatible with .NET Framework 3.0). Follow the steps below before running the sample application:

-          Create a certificate

-          Modify the serviveCertificate elements defined in both client and service App.config files to reference your new certificate (you may decide to change the FindType as well)

-          Specify a correct DNS identity value for the client endpoints

Let me know what you thought of this article...

References:

-          Selecting a WCF Credential type

-          Bypassing certificate validation

-          Common WCF Security Scenarios

-          Transport Security with Basic Authentication

-          Service Identity and Authentication

-          How To Use the ASP.NET Membership Provider

Posted: Friday, October 05, 2007 5:27 PM by pedramr
Filed under: ,

Attachment(s): WCFSecurity.zip

Comments

JanW said:

Thanks for the guide. However, one of the issues here is that any exceptions thrown in the Validate() method will not be reported back to the client properly. All you will get is a MessageSecurityException. This has been reported several times (e.g. here: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=575748&SiteID=1) Unfortunatley Microsoft did not come up with an adequate response yet.

# October 24, 2007 8:51 AM

Jon said:

I created a certificate "CN=SignedByCA" and updated the App.Config files to refer to its thumbprint. Now when I try to start the host, I get the following exception on host.Open():

The certificate 'CN=SignedByCA' must have a private key that is capable of key exchange. The process must have access rights for the private key.

I'm not sure how to give the host access to the private key. I'm starting the host process using VS 2008.

Regards,

Jon

# November 28, 2007 3:31 AM

Diego said:

I'm having the same issue Jon mentioned. I'm also getting the message:

The certificate 'CN=SignedByCA' must have a private key that is capable of key exchange. The process must have access rights for the private key.

Please.... help :S

# January 10, 2008 2:43 PM

Dimitris-Ilias Gkanatsios said:

To the two above: Use the FindPrivateKey utility located in the WCF samples to find the location of the private key, and then set the permissions accordingly.

I spent many hours today while having the same problem, and I came up with the following solution

To install a self signed certificate

makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe

certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r LocalMachine -s TrustedPeople

To use the FindKeyUtility

FindPrivateKey.exe TrustedPeople LocalMachine Private key directory: C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys Private key file name: 756e9ecb7bb8ed83bf80031497479997_8a4ee4f0-1f8d-4d2e-b1bf-fff1d5b15e61

And then, you can go to the specified folder and change the permissions...

Moreover, I needed to set this in the client's config file

    <behaviors>

       <endpointBehaviors>

         <behavior name="ClientCertificateBehavior">

           <clientCredentials>

             <serviceCertificate>

                 <authentication certificateValidationMode="PeerOrChainTrust" />

             </serviceCertificate>

           </clientCredentials>

         </behavior>

       </endpointBehaviors>

     </behaviors>

and add this to the endpoint configuration

behaviorConfiguration="ClientCertificateBehavior"

Finally, pay attention to the

<identity>

                   <dns value="localhost" />

               </identity>

element, in the client.

The dns value must much the one in the certificate.

Good luck!!

# January 31, 2008 9:04 PM

Thiarley Fontenele said:

Hi,

If I authenticate the user using peertrust, How can I get his certificate inside the Operation Contract ?

I need the certificate to get others informations.

# February 1, 2008 9:00 AM

Jernej Logar said:

Hi!

I was also getting the message:

The certificate 'CN=SignedByCA' must have a private key that is capable of key exchange. The process must have access rights for the private key.

I solved that by importing the certificate together with the private key, using a pfx fiel which I generated wtih pvk2pfx.

# March 11, 2008 10:19 AM

alik levin's said:

This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case

# April 20, 2008 12:28 AM

Fernando Alves said:

In some of my implemented OperationContract methods i need to log with others method informations, and console output the validated credentials (username/password), how can i get the respective instanciated credential values?

# May 11, 2008 11:25 AM

Fernando Alves said:

Nevermind, ServiceSecurityContext.Current.PrimaryIdentity.Name

# May 11, 2008 12:18 PM

江南白衣 said:

This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case it is useful.

# May 11, 2008 12:22 PM

Arjan Hordijk said:

I had the same problem.

These were the steps I took to solve the problem:

I removed the generated personal key from the store and issued the following request: makecert -sk SignedByCA -iv TempCA.pvk -n "CN=localhost" -ic TempCA.cer SignedByCA.cer -sr LocalMachine -ss My -sky exchange -pe

The created certificate was added to the personal certifcate store of the local computer.

After placing this certificate in the personal certificate store of the current user (drag and drop) the error was gone.

Hope this will help.....

We are not the only ones (Also see this post: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1180892&SiteID=1)

# July 17, 2008 5:08 AM

Mathew Upchurch said:

Great article but my problem is I'm authenticated on my web site already (setting the generic principal)... not I need to call my services layer... but I no longer have password available...  any best practices for how to deal with this?

# July 23, 2008 4:39 PM

VG said:

My Service is hosted under IIS with SSL enabled.

This works without SSL enabled, but doesn't work with SSL on.

Any tips?

# July 24, 2008 1:55 PM

John Doe said:

Good post.

Complemented with http://www.digwin.com/view/howto-use-makecert-for-trusted-root-certification-authority-and-ssl-certificate-issuance , it made for an easy implementation of UserName validation. : )

# August 14, 2008 4:40 AM

angeltq said:

Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'CurrentUser', FindType 'FindByThumbprint', FindValue '8e f9 c6 6f 4e a0 0c 49 4f 84 69 fb de c6 a7 e1 79 01 5b 6e'.

Help me!

# September 23, 2008 4:22 AM

Gr1nch said:

Anyone know how to catch any exception we throw in our Validate() function so we might have some means of returning a code for why validation failed? It would seem that regardless of what SecurityTokenException I throw, the only exception actually caught on the client side is the generic one. I can see my exception if I run diagnostics, but I need the client to see it to detect such things as lockout and other failure reasons...

# November 18, 2008 12:27 PM

Mike said:

2 Gr1nch

1) Throw a FaultException from Validate(...)

2) Catch MessageSecurityException on the client.

3) In the InnerException property you will find the FaultException you threw.

Keep in mind: generic FaultExceptions don't work here as a filter on client side, but you can, for example, use FaultCode during FaultException initialization to be sure that an InnerException the client got from MessageSecurityException is indeed the exception you threw in Validate(...).

# April 28, 2009 1:59 PM

#.think.in said:

#.think.in infoDose #28 (29th Apr - 8th May)

# May 15, 2009 4:32 AM

#.think.in said:

#.think.in infoDose #28 (29th Apr - 8th May)

# May 30, 2009 6:12 PM

Thankful said:

Exactly what I needed!!!

Thanks a whole lot for the post.

# October 14, 2009 2:28 PM

Karan said:

Hi, I am getting this exception as described in the test above.

“Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was 'X' but the remote endpoint provided DNS claim 'Y'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'Y' as the Identity property of EndpointAddress when creating channel proxy.”

I am using an endpoint identity as SPN. Any idea how to get this to work with endpoint Identity set as SPN.

Thanks.

# November 2, 2009 11:28 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker