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:
<security mode="Message" >
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:
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:
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 =
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):
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...
- 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
PingBack from http://www.artofbam.com/wordpress/?p=5519
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.
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.
I'm having the same issue Jon mentioned. I'm also getting the message:
Please.... help :S
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
<authentication certificateValidationMode="PeerOrChainTrust" />
and add this to the endpoint configuration
Finally, pay attention to the
<dns value="localhost" />
element, in the client.
The dns value must much the one in the certificate.
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.
I was also getting the message:
I solved that by importing the certificate together with the private key, using a pfx fiel which I generated wtih pvk2pfx.
This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case
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?
This is a digest of WCF Security resources I was collecting for some time. Drop me a comment in case it is useful.
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)
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?
My Service is hosted under IIS with SSL enabled.
This works without SSL enabled, but doesn't work with SSL on.
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. : )