WCF Service With SQL Membership and Roles Provider

Introduction

 
Today I am going to write about the WCF and ASP.NET Membership Provider & Roles Provider.
 

How we can use Membership Provider in the WCF

 
How will we pass Client Credentials from the client. The WCF Client may be a Console Application, Windows Application or Web Application.
 
I have gone through many related articles and blogs which I am going to write about. There was not enough information about both the Membership Provider and the Roles Provider.
 
Purpose: To build a solution where a WCF service will manage Authentication and Roles Management.
 
Codes: Ok. I am going to start coding for a WCF Service with Membership and Roles.
 
Step 1: First of all we will create a new project. The project type should be WCFServiceLibrary. We will not change anything in the Service Interface.
 
We'll only add the "Principal Permission" attribute above the method. The method will execute only if the user has an admin right because we have specified in the Principal Permission Attribute.
  1. [PrincipalPermission(SecurityAction.Demand, Role = "admin")]  
  2. public string GetData(int value)  
  3. {  
  4.     //if (HttpContext.Current.Session["Result"] != null)  
  5.     //    return string.Format("You entered: {0}", value);  
  6.     return string.Format("You entered: {0}", value);  
  7. }  
Step 2: Now we will add ConnectionString, Membership Provider and Roles Provider in app.config file.
  1. <connectionStrings>  
  2.   <add name="DefaultConnection" connectionString="Data Source={ServerName};Initial Catalog={DatabaseName};Integrated Security=True"  
  3.     providerName="System.Data.SqlClient" />  
  4. </connectionStrings>  
  5. <system.web>  
  6.   <compilation debug="true"/>  
  7.   <authentication mode="Forms"/>  
  8.   <membership defaultProvider="DefaultMembershipProvider">  
  9.     <providers>  
  10.       <clear />  
  11.       <add name="DefaultMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />  
  12.     </providers>  
  13.   </membership>  
  14.   <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">  
  15.     <providers>  
  16.       <clear />  
  17.       <add connectionStringName="DefaultConnection" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />  
  18.     </providers>  
  19.   </roleManager>  
  20. </system.web>  
Step 3: We will test WCF test application with default endpoint. 
  1. <bindings>  
  2.       <wsHttpBinding>  
  3.         <binding name="wsHttpEndpointBinding">  
  4.           <security>  
  5.             <message clientCredentialType="UserName" />  
  6.           </security>  
  7.         </binding>  
  8.       </wsHttpBinding>  
  9. </bindings>  
  10. <services>  
  11.       <service name="WCFServiceWithMemberShip.Service1" behaviorConfiguration="ServiceBehavior">  
  12.         <host>  
  13.           <baseAddresses>  
  14.             <add baseAddress="http://localhost:8733/Design_Time_Addresses/WCFServiceWithMemberShip/Service1/"   />  
  15.           </baseAddresses>  
  16.         </host>  
  17.         <endpoint address="" bindingConfiguration="wsHttpEndpointBinding" binding="wsHttpBinding"  
  18.                   contract="WCFServiceWithMemberShip.IService1">  
  19.         </endpoint>  
  20.         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  21.       </service>  
  22. </services>  
In the above endpoint we are using wsHttpBinding because the security is Message type. It won't work with basichttpBinding.
 
Step 4: Now we will see below the most important thing. You can see the highlighted text below; we have configured the RolesPorvider and Membership Provider for the service.
  1. <behaviors>  
  2.   <serviceBehaviors>  
  3.     <behavior name="ServiceBehavior">  
  4.       <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="AspNetSqlRoleProvider">  
  5.       </serviceAuthorization>  
  6.       <serviceMetadata httpGetEnabled="true" />  
  7.       <serviceDebug includeExceptionDetailInFaults="false" />  
  8.       <serviceCredentials>  
  9.         <clientCertificate >  
  10.           <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>  
  11.           <certificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />  
  12.         </clientCertificate>  
  13.         <serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />  
  14.         <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"  
  15.           membershipProviderName="DefaultMembershipProvider" />  
  16.       </serviceCredentials>  
  17.     </behavior>  
  18.   </serviceBehaviors>  
  19. </behaviors>  
  20. </configuration>
Step 5: Now we will consume the WCF service in the ConsoleApplication. We just use a service reference in the Client application.
 
Client config file will look like this.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.     <startup>  
  4.         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
  5.     </startup>  
  6.     <system.serviceModel>  
  7.         <bindings>  
  8.             <wsHttpBinding>  
  9.                 <binding name="WSHttpBinding_IService1">  
  10.                     <security>  
  11.                         <message clientCredentialType="UserName" />  
  12.                     </security>  
  13.                 </binding>  
  14.             </wsHttpBinding>  
  15.         </bindings>  
  16.         <client>  
  17.             <endpoint address="http://localhost:8733/Design_Time_Addresses/WCFServiceWithMemberShip/Service1/"  
  18.                 binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"  
  19.                 contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">  
  20.                 <identity>  
  21.                     <certificate encodedValue="AwAAAAEAAAAUAAAAjFYTFAWcfK16VR04unfMDAglktIgAAAAAQAAANUBAAAwggHRMIIBOqADAgECAhB  
  22. Xl/pS1MZAiE9XIoZU96WeMA0GCSqGSIb3DQEBBQUAMBQxEjAQBgNVBAMTCWxvY2FsaG9zdDAeFw0xMjA0MTIxMjU5NDRaFw0yMjA0MTIwMDAwMDBa  
  23. MBQxEjAQBgNVBAMTCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqHHfPvuMcvaSxEijFMYbTOzqezdntfUzjpj1p5hJwF+q6UOnm  
  24. URO5Inh90VGS1JnYYMarb21UOYtQr2L1WulzrTHY402WPDnepsi6FRpufMV7FDSb+MDtt/8k0dtF4y9xBH6OUuW3KP/2uE18Fw8xaLMkd/wUjr+s84iEtlRsQk  
  25. CAwEAAaMkMCIwCwYDVR0PBAQDAgSwMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBBQUAA4GBAE+6Ed40e+oY5Q  
  26. 2dVt3BgSiSGMlXYJ4Yvmu+h8KnbTa9jFhbgi76gj8or4QFK0heCBZCzm/k9xdXKkCYt/WEC/CAL9tPEXJb7vS+yjObBeukA9STw888K65zUup5HgvJdad1Zg5z9  
  27. IXuCf81VnHYI3S5K+rdOlGs+d3wlhh3Em8Q" />  
  28.                 </identity>  
  29.             </endpoint>  
  30.         </client>  
  31.     </system.serviceModel>  
  32. </configuration>  
Step 6: Now we will call the service in the client application:
  1. static void Main(string[] args)  
  2. {  
  3.      using (ServiceReference1.Service1Client client = new ServiceReference1.Service1Client())  
  4.  {  
  5.      client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;  
  6.    
  7.         client.ClientCredentials.UserName.UserName = "{username}";  
  8.         client.ClientCredentials.UserName.Password = "{Password}";  
  9.         Console.WriteLine(client.GetData(1));  
  10.         Console.ReadKey();  
  11.     }  
  12. }  
I hope now you can use membership and roles in WCF. If anyone has any questions, please feel free to make your comments.


Similar Articles