Use Asp.Net Membership provider with a WCF .svc service

Yesterday I literally lost 4 hours trying to do the following thing: Exposing a wcf service with wsHttpBinding, and using the same membership database used by the site. I encountered many problems, and I decided to write this post to explain the steps that makes everything work for me. First of all you need to know that fact: if you want to use membership in a wcf service exposed with wsHttpBinding you need to use certificates, and this causes most of the problems.

You need to create certificates in the server that will run the service, to accomplish this you should configure a Certificate Authority, but for testing purpose you can use MakeCert.exe as described here. Even if you are not familiar with certificate, here is the two command lines you need to type at vs command prompt (with administrative privilege if you work in windows vista/7 ).

makecert -n "CN=AlkCA" -r -sv AlkCa.pvk AlkCa.cer

This creates two files, one is the private key of this temp certificate authority, the other is the certificate of the authority. Now you need to create the certificate to use with wcf, using these files just created.

makecert -sk SignedByCA -iv AlkCa.pvk -n "CN=localhost" -ic AlkCa.cer -sr LocalMachine -ss My -sky exchange -pe

The CN=localhost must be the address you use to expose the service. If the service will go on a server called ServerXXX you need to create the certificate with CN=ServerXXX. Just to be clear, if you will access your service with the address http://servername:port/servicename.svc you must create with CN=servername. moreover does not forget to create with –sky exchange. Now that you have the certificate open the mmc console, typing mmc at command prompt. The mmc opens, then goes to File->add/remove snap in, choose certificate, then choose computer account, then local computer. Now verify that the new certificate is in place.


Now you need to configure web.config on the web application that will host the site. First of all configure the membership as usual, first of all the connectionstring.

    <add name="SqlConn" connectionString="Database=auth;Server=localhost\sql2008;User=blabla;Pwd=blabla" providerName="System.Data.SqlClient" />

Then Membership and Role provider.

<roleManager defaultProvider="SqlRoleProvider" enabled="true" cacheRolesInCookie="true">
    <add name="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="SqlConn" applicationName="/" />
<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
    <clear />
      ... />

Now you need to instruct WCF to use certificate and membership. Here is the endpoint as it should be defined in the server.

<service behaviorConfiguration="Web.HelloWorldBehavior" name="TestService.HelloWorld">
    <endpoint address="" binding="wsHttpBinding" contract="TestService.IHelloWorld"
            <dns value="localhost" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

The value for the <dns value=”xxx” /> must be the same of the certificate. In this simple example I simply used localhost, but do not forget to use the real name that you will use to expose the service. The bindingConfiguration is named “mb” and is the one that instruct wcf that we are expecting username/password in the header of the messages.

    <binding name="mb">
      <security mode="Message">
        <message clientCredentialType="UserName"/>

I used security mode Message and credentialType UserName. This is the reason why we need certificates, because ws* requires that username credentials must not be sent in clear text. Finally you need to tell wcf where to find certificate to use, this is done in the behaviour Web.HelloWorldBehaviour

    <behavior name="Web.HelloWorldBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="SqlRoleProvider" />
          <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" 
                              storeLocation="LocalMachine" storeName="My" />

          <userNameAuthentication userNamePasswordValidationMode ="MembershipProvider"
              membershipProviderName ="SqlMembershipProvider"/>

You can see that the certificate is specified with ServiceCertificate where findValue is the value used for CN=localhost, and the certificate is stored in local machine in personal/certificate as I explained before. Now you can browse to the service and verify that everything works. It is now possible that you get the exception:

Keyset does not exist

This happens because the user used to run the application pool needs permission to access certificates. Return in mmc and give to that user needed permission


In my example I simply used NetworkService to run the application so I give to network service the appropriate rights.


Now you should be able to browse the service with no problem, now it is time to configure the client. Since we are using certificates, we need to do a couple of things in all clients computer: install the certificate localhost, and install the certificate authority as trusted one. To accomplish this step you first need to export generated certificate from the server


Choose not to export the private key, export it in DER encoded binary X.509, and choose destination directory, you will obtain a .cer file. Now move to the client computer (usually it is a good thing to first test client on the server machine to avoid firewall problem etc etc) open mmc console and add another snap/in , choose certificate then My user. These operations must be executed for each client that will access the service. Goes to the Personal/Certificates and import the localhost.cer certificate just created.


This is not enough, because this certificate was issued by a not trusted temporary certificate authority, it is not a trusted one. You need to add the temp CA into trusted certification authority:


By clicking “Import” you need to browse where you created the two pvk and cer file (the very first step of this tutorial), and you need to import the file AlkCa.cer, the certificate file for the temporary certification authority. Clearly you need to send those two files to each client computer, but keep secret the pck file. Now you should see the CA in the list of trusted root certification authorities. Now create a windows form application, set a reference to the service and goes to app.config. In the behaviors section you need to configure certificates.

    <behavior name="certForClient">
        <clientCertificate findValue="localhost" x509FindType="FindBySubjectName"
                                    storeLocation="CurrentUser" storeName="My"/>

As you can verify the location is now CurrentUser because the certificate is stored in the certificate store of the current user. This guarantee maximum security, if someone else log in into computer, it does not have certificate to access the service, because the service is bound to that user only. Finally you need to be sure that the endpoint is configured correctly.

   <endpoint address="http://localhost:10001/HelloWorld.svc" binding="wsHttpBinding"
       bindingConfiguration="WSHttpBinding_IHelloWorld" contract="HelloWorld.IHelloWorld"
       name="WSHttpBinding_IHelloWorld" behaviorConfiguration="certForClient">
           <dns value="localhost" />

You need to verify that behaviorConfiguration is ok and that the address of the service is localhost, the exact name of the certificate. Now you can try to access the server from the client with this code.

using (HelloWorld.HelloWorldClient client = new WindowsFormsApplication1.HelloWorld.HelloWorldClient()) {
    client.ClientCredentials.UserName.UserName = "Dev";
    client.ClientCredentials.UserName.Password = "xxxxxx";
    MessageBox.Show(client.HelloWorld().ToString()) ;

I created in authentication database a user named Dev, that belongs to the role “Developers”.


The method HelloWorld in the concrete implementation of the service requires a specific role

[PrincipalPermission(SecurityAction.Demand, Role="Developers")]
int IHelloWorld.HelloWorld()
   ServiceSecurityContext context = ServiceSecurityContext.Current; 
   return 42;

The PrincipalPermission attribute requires that to call this method you need to belong to role “Developers”. You can start the client and verify that it is able to call the server correctly. Now it is possible that you gets the exception.

The X.509 certificate CN=localhost chain building failed. The certificate that was used has a trust chain that cannot be verified. Replace the certificate or change the certificateValidationMode. The revocation function was unable to check revocation for the certificate

There are a lot of posts dealing with this problem around in the internet, but if you read with attention the error is The revocation function was unable to check revocation for the certificate, and is due to the fact that certificate was not issue by a real Certificate Authority, so the client is not able to verify if the certificate was revocated. You need to change the client app.config telling wcf not to check revocation.

    <behavior name="certForClient">
        <serviceCertificate >
          <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>
        <clientCertificate findValue="localhost" x509FindType="FindBySubjectName"
                                    storeLocation="CurrentUser" storeName="My"/>

As you can see I set revocationMode to “NoCheck” this is usually enough to solve the problem. After everything works you can verify what is happening with a user that does not belongs to Developers role..

using (HelloWorld.HelloWorldClient client = new WindowsFormsApplication1.HelloWorld.HelloWorldClient())
    client.ClientCredentials.UserName.UserName = "Test";
    client.ClientCredentials.UserName.Password = "xxx";

I’ve created a valid user Test, that belongs only to role “Testers”, and when you try to call the HelloWorld method you will get an exception “access denied” because the user does not belongs to requested role.

Sometimes you can encounter the following exception.

An unsecured or incorrectly secured fault was received from the other party

This happens when there is some error in the server, the most common one is a wrong configuration of the authentication database, or authentication. Verify with the appropriate web management that everything is ok in the web.config, verify connection string to the auth database, and verify that authentication mode=”Forms” and not “Windows”.


If you still are receiving this exception try to access the service through an unsecured basicHttpBinding or look at message exchange with fiddler, that usually reveals the real exception that is occurred in the server.

These steps worked for me in a windows server 2008 environment and in Windows7 64 bit environment. Never tested in windows server 2003, xp or vista, but everything should be the same. You can find my example here.



Published by

Ricci Gian Maria

.Net programmer, User group and community enthusiast, programmer - aspiring architect - and guitar player :). Visual Studio ALM MVP

12 thoughts on “Use Asp.Net Membership provider with a WCF .svc service”

  1. Actually I used for a production software so I do not have working sample that I can post here. I could try to extract a sample service, but basically the difficult part is the one related to issuing certificates, If you really need I can try to extract a working sample.

  2. Hi, Just wanted to thank you for this…you did an awesome job…I got it running after slowly working through your steps.

    I do have one existing problem and I am googling the hell out of it and cannot come up with an answer. I think it’s a simple configuration issue, but really cannot get it to work….

    I am trying to access the HttpContext.Current from within my service…

    I have this set in my service:
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MembershipService : IMembershipService

    and I also have

    in my web.config of my app and my service app.config (which turns to web.config when deployed)

    do you have any idea why I cannot access HttpContext? when I debug it, it says

    bool enabled = ServiceHostingEnvironment.AspNetCompatibilityEnabled;

    enabled is TRUE….

    This works fine:
    Thread.CurrentPrincipal.Identity.Name: ** WORKS
    OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name: ** WORKS
    HttpContext.Current.User.Identity.Name: ** DOESN’T WORK…NULL


  3. Because HttpContext usually does not work for WCF Services, even with AspNetCompatibilityRequirements it is possible that the above code don’t work.

    Can you specify what is null in the instruction


    if the Current is null it means that no httpcontext was created, if is not null and User is null is probably because engine is expecting someone to login through standard membership api, so you need cookie on che client and so on, but this is only a possibility.


  4. hi.. i am also getting the error x.509 chain building failed. I tried to follow as you said. But i couldnt find the piece of code that you specified in my client config file. But when i check in my MMC i could see my revocation list installed in there.

  5. Revocation list should be related to denied certificates. The chain building failed usually is due to some certificate errors, have you some inner exception to better understand what is happening?

    Feel free to write to my email that is alkampfer [at] nablasoft [dot] com


  6. Here’s a stupid question: I never got the ‘Keyset does not exist’…does this mean I did something wrong?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.