Showing posts with label Anil's. Show all posts
Showing posts with label Anil's. Show all posts

Tuesday, December 13, 2011

ASP.NET Web Application Security


ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods:
  • Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos).
  • Forms authentication, in which you create a login page and manage authentication in your application.
  • Client Certificate authentication
ASP.NET controls access to site information by comparing authenticated credentials, or representations of them, to NTFS file system permissions or to an XML file that lists authorized users, authorized roles (groups), or authorized HTTP verbs.
This section contains topic that describe the specifics of ASP.NET security in details.

How ASP.NET Security Works
Securing Web sites is a critical, complex issue for Web developers. Protecting a site requires careful planning, and Web site administrators and programmers must have a clear understanding of the options for securing their site.
ASP.NET works in concert with the Microsoft .NET Framework and Microsoft Internet Information Services (IIS) to help provide Web application security. To help protect your ASP.NET application, you should perform the two fundamental functions described in the following table
SecurityFunction 
Description
Authentication
Helps to verify that the user is, in fact, who the user claims to be. The application obtains credentials (various forms of identification, such as name and password) from a user and validates those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity.
Authorization
Limits access rights by granting or denying specific permissions to an authenticated identity.
IIS can also grant or deny access based on a user's host name or IP address. Any further access authorization is performed by NTFS file access permission's URL authorization.
It is helpful to understand how all the various security subsystems interact. Since ASP.NET is built on the Microsoft .NET Framework, the ASP.NET application developer also has access to all the built-in security features of the .NET Framework, such as code access security and role-based user-access security. For details about the security capabilities of ASP.NET, see 

You can configure a Web service to require Secure Sockets Layer (SSL) to protect sensitive data sent between the client and the service. SSL provides:
  • Message integrity. This ensures that messages are not modified while in transit.
  • Message confidentiality. This ensures that messages remain private while in transit.
This How To describes how to configure a Web service to require SSL and how to call the Web service from an ASP.NET client application by using the HTTPS protocol.

Summary of Steps

This article includes the following steps:
  • Step 1. Install Server Certificates on the Web Server
  • Step 2. Create a Simple Web Service
  • Step 3. Configure the Web Service Virtual Directory to Require SSL
  • Step 4. Test the Web Service Using a Browser
  • Step 5. Install the Certificate Authority's Certificate on the Client Computer
  • Step 6. Develop a Web Application to Call the Serviced Component

Step 1. Install Server Certificates on the Web Server

For information about installing Web server certificates on a Web server, see

Step 2. Create a Simple Web Service

To create a simple Web service on the Web service host computer
  1. Start Visual Studio .NET and create a new C# ASP.NET Web Service application called SecureMath.
  2. Rename service1.asmx as math.asmx.
  3. Open math.asmx.cs and rename the Service1 class as math.
  4. Add the following Web method to the math class.
5.   [WebMethod]
6.  public long Add(long operand1, long operand2)
7.  
8.    return (operand1 + operand2);
9.  }
  1. To create the Web service, click Build Solution on the Build menu.

Step 3. Configure the Web Service Virtual Directory to Require SSL

Your Web service runs on Internet Information Services (IIS) and relies on IIS to provide SSL support.
This procedure assumes that you have a valid server certificate installed on your Web server. For more information about installing Web server certificates, see

To use IIS to configure your Web service's virtual directory for SSL
  1. On the Web service host computer, start IIS.
  2. Navigate to the SecureMath virtual directory.
  3. Right-click SecureMath, and then click Properties.
  4. Click the Directory Security tab.
  5. Under Secure communications, click Edit.
If Edit is unavailable, it is likely that a Web server certificate is not installed.
  1. Select the Require secure channel (SSL) check box.
  2. Click OK, and then OK again.
  3. In the Inheritance Overrides dialog box, click Select All, and then click OK to close the SecureMath properties dialog box.
This applies the new security settings to all subdirectories in the virtual directory root.

Step 4. Test the Web Service Using a Browser

This procedure ensures that the Web server certificate is valid and has been issued by a Certification Authority (CA) that is trusted by the client computer.
To call the Web service using SSL from Internet Explorer
  1. Start Internet Explorer on the client computer and browse (using HTTPS) to the Web service. For example:
2.  https://WebServer/securemath/math.asmx
The Web service test page should be displayed by the browser.
  1. If the Web service test page is displayed successfully, close Internet Explorer and go to Procedure 5, "Develop a Web Application to Call the Serviced Component."
  2. If the Security Alert dialog box, as illustrated in Figure 1, is displayed, click View Certificate to see the identity of the issuing CA for the Web server certificate. You must install the CA's certificate on the client computer. This is described in Procedure 4, "Install the Certificate Authority's Certificate on the Client Computer."
  3. Close Internet Explorer.

Step 5. Install the Certificate Authority's Certificate on the Client Computer

This procedure installs the issuing CA's certificate on the client computer as a trusted root certificate authority. The client computer must trust the issuing CA in order to accept the server certificate without displaying the Security Alert dialog box.
If you use Microsoft Certificate Services as a CA within your Windows domain
Perform this procedure only if your Web server certificate was issued by a Microsoft Certificate Services CA. Otherwise, if you have the CA's .cer file, go to Step 8.
  1. Start Internet Explorer and browse to http:// hostname/certsrv, where hostname is the name of the computer where Microsoft Certificate Services that issued the server certificate is located.
  2. Click Retrieve the CA certificate or certificate revocation list, and then click Next.
  3. Click Install this CA certification path.
  4. In the Root Certificate Store dialog box, click Yes.
  5. Browse to Web service using HTTPS. For example:
6.  https://WebServer/securemath/math.asmx
The Web service test page should now be correctly displayed by the browser, without a Security Alert dialog box.
You have now installed the CA's certificate in your personal trusted root certificate store. To be able to call the Web service successfully from an ASP.NET page, you must add the CA's certificate to the computer's trusted root store.
  1. Repeat Steps 1 and 2, click Download CA certificate, and then save it to a file on your local computer.
  2. Now perform the remaining steps, if you have the CA's .cer certificate file.
  3. On the taskbar, click Start, and then click Run.
  4. Type mmc, and then click OK.
  5. On the Console menu, click Add/Remove Snap-in.
  6. Click Add.
  7. Select Certificates, and then click Add.
  8. Select Computer account, and then click Next.
  9. Select Local Computer: (the computer this console is running on), and then click Finish.
  10. Click Close, and then OK.
  11. Expand Certificates (Local Computer) in the left pane of the MMC snap-in.
  12. Expand Trusted Root Certification Authorities.
  13. Right-click Certificates, point to All Tasks, and then click Import.
  14. Click Next to move past the Welcome dialog box of the Certificate Import Wizard.
  15. Enter the path and filename of the CA's .cer file.
  16. Click Next.
  17. Select Place all certificates in the following store, and then click Browse.
  18. Select Show physical stores.
  19. Expand Trusted Root Certification Authorities within the list, and then select Local Computer.
  20. Click OK, click Next, and then click Finish.
  21. Click OK to close the confirmation message box.
  22. Refresh the view of the Certificates folder within the MMC snap-in and confirm that the CA's certificate is listed.
  23. Close the MMC snap-in.

Step 6. Develop a Web Application to Call the Web Service

This procedure creates a simple ASP.NET Web application. You will use this ASP.NET Web application as the client application to call the Web service.
To create a simple ASP.NET Web application
  1. On the Web service client computer, create a new C# ASP.NET Web application called SecureMathClient.
  2. Add a Web reference (by using HTTPS) to the Web service.
    1. Right-click the References node within Solution Explorer, and then click Add Web Reference.
    2. In the Add Web Reference dialog box, enter the URL of your Web service. Make sure you use an HTTPS URL.
Note   If you have already set a Web reference to a Web service without using HTTPS, you can manually edit the generated proxy class file and change the line of code that sets the Url property from an HTTP URL to an HTTPS URL.
    1. Click Add Reference.
  1. Open WebForm1.aspx.cs and add the following using statement beneath the existing using statements.
4.  using SecureMathClient.WebReference1;
  1. View WebForm1.aspx in Designer mode and create a form like the one illustrated in Figure 2 using the following IDs:
o    operand1
o    operand2
o    result
o    add
Figure 2. WebForm1.aspx form
                        Double-click the Add button to create a button-click event hander.
                        Add the following code to the event handler.
             private void add_Click(object sender, System.EventArgs e)
             {
               math mathService = new math();
               int addResult = (int) mathService.Add( Int32.Parse(operand1.Text), 
                                                   Int32.Parse(operand2.Text));
               result.Text = addResult.ToString();
             }
                        On the Build menu, click Build Solution.
                        Run the application. Enter two numbers to add, and then click the Add button.
                         The Web application will call the Web service using SSL.

Additional Resources


To create a Web application with a logon page
  1. Start Microsoft Visual Studio® .NET and create a new C# ASP.NET Web Application named FormsAuthAD.
  2. Use Solution Explorer to rename WebForm1.aspx as Logon.aspx.
  3. Add a new assembly reference to System.DirectoryServices.dll. This provides access to the System.DirectoryServices namespace that contains managed types to help with Active Directory querying and manipulation.
  4. Add the controls listed in Table 1 to Logon.aspx to create a simple logon form.
Table 1. Logon.aspx controls
Control Type
Text
ID
Label
Domain Name:
-
Label
User Name:
-
Label
Password
-
Text Box
-
txtDomainName
Text Box
-
txtUserName
Text Box
-
txtPassword
Button
Log On
btnLogon
Label

lblError
  1. Set the TextMode property of txtPassword to Password.
  2. In Solution Explorer, right-click FormsAuthAd, point to Add, and then click Add Web Form.
  3. In the Name field, type default.aspx, and then click Open.
  4. In Solution Explorer, right-click default.aspx, and then click Set As Start Page.
  5. Double-click default.aspx to display the page load event handler.
  6. Add the following code to the event handler to display the identity name associated with the current Web request.
11.Response.Write( HttpContext.Current.User.Identity.Name );

Step 2. Configure the Web Application for Forms Authentication

This procedure edits the application's Web.config file to configure the application for Forms authentication.
To configure the Web application for forms authentication
  1. Use Solution Explorer to open Web.config.
  2. Locate the <authentication> element and change the mode attribute to Forms.
  3. Add the following <forms> element as a child of the authentication element and set the loginUrl, name, timeout, and path attributes as shown in the following.
4.  <authentication mode="Forms">
5.    <forms loginUrl="logon.aspx" name="adAuthCookie" timeout="60"
6.      path="/">
7.    </forms>
8.  </authentication>
  1. Add the following <authorization> element beneath the <authentication> element. This will allow only authenticated users to access the application. The previously establish loginUrl attribute of the <authentication> element will redirect unauthenticated requests to the logon.aspx page.
10.<authorization> 
11.  <deny users="?" />
12.  <allow users="*" />
13.</authorization>
  1. Save Web.config.
  2. Start the IIS Microsoft Management Console (MMC) snap-in.
  3. Right-click the application's virtual directory, and then click Properties.
  4. Click the Directory Security tab, and then click the Edit button in the Anonymous access and authentication control group.
  5. Select the Anonymous access check box and clear the Allow IIS to control password check box.
  6. Because the default anonymous account IUSR_MACHINE does not have permission to access Active Directory, create a new least privileged account and enter the account details in the Authentication Methods dialog box.
  7. Click OK, and then click OK again to close the Properties dialog box.
  8. Return to Visual Studio .NET and add an <identity> element beneath the <authorization> element in Web.config and set the impersonate attribute to true. This causes ASP.NET to impersonate the anonymous account specified earlier.
22.<identity impersonate="true" />
As a result of this configuration, all requests to the application will run under the security context of the configured anonymous account. The user will provide credentials through the Web form to authenticate against Active Directory, but the account used to access Active Directory will be the configured anonymous account.

Step 3. Develop LDAP Authentication Code to Look Up the User in Active Directory

This procedure adds a new helper class to the Web application to encapsulate the LDAP code. The class will initially provide an IsAuthenticated method to validate a supplied domain, user name, and password against an Active Directory user object.
To develop LDAP authentication code to look up the user in Active Directory
  1. Add a new C# class file called LdapAuthentication.cs.
  2. Add a reference to the System.DirectoryServices.dll assembly.
  3. Add the following using statements to the top of LdapAuthentication.cs.
4.  using System.Text;
5.  using System.Collections;
6.  using System.DirectoryServices;
  1. Rename the existing namespace as FormsAuthAD.
  2. Add two private strings to the LdapAuthentication class; one to hold the LDAP path to Active Directory and the other to hold a filter attribute used for searching Active Directory.
9.  private string _path;
10.private string _filterAttribute;
  1. Add a public constructor that can be used to initialize the Active Directory path.
12.public LdapAuthentication(string path)
13.{
14.  _path = path;
15.}
  1. Add the following IsAuthenticated method that accepts a domain name, user name and password as parameters and returns bool to indicate whether or not the user with a matching password exists within Active Directory. The method initially attempts to bind to Active Directory using the supplied credentials. If this is successful, the method uses the DirectorySearcher managed class to search for the specified user object. If located, the _path member is updated to point to the user object and the _filterAttribute member is updated with the common name attribute of the user object.

Step 4. Develop LDAP Group Retrieval Code to Look Up the User's Group Membership

This procedure extends the LdapAuthentication class to provide a GetGroups method, which will retrieve the list of groups that the current user is a member of. The GetGroups method will return the group list as a pipe separated string, as in the following.
"Group1|Group2|Group3|"
To develop LDAP group retrieval code to look up the user's group membership
  1. Add the following implementation of the GetGroups method to the LdapAuthentication class.

Step 5. Authenticate the User and Create a Forms Authentication Ticket

This procedure implements the btnLogon_Click event handler to authenticate users. For authenticated users, you will then create a Forms authentication ticket that contains the user's group list. You will then redirect the user to the original page that they requested (before being redirected to the logon page).
To authenticate the user and create a forms authentication ticket
  1. Return to the Logon.aspx form and double-click the Log On button to create an empty btnLogon_Click event handler.
  2. At the top of the file add the following using statement beneath the existing using statements. This provides access to the FormsAuthentication methods.
3.  using System.Web.Security;
  1. Add code to create a new instance of the LdapAuthentication class initialized to point to your LDAP Active Directory, as shown in the following code. Remember to change the path to point to your Active Directory server.
5.  // Path to you LDAP directory server.
6.  // Contact your network administrator to obtain a valid path.
7.  string adPath = 
8.    "LDAP://yourCompanyName.com/DC=yourCompanyName,DC=com"; 
9.  LdapAuthentication adAuth = new LdapAuthentication(adPath);
  1. Add the code that follows to perform the following steps:
    1. Authenticate the caller against Active Directory.
    2. Retrieve the list of groups that the user is a member of.
    3. Create a FormsAuthenticationTicket that contains the group list.
    4. Encrypt the ticket.
    5. Create a new cookie that contains the encrypted ticket.
    6. Add the cookie to the list of cookies returned to the user's browser.

Step 6. Implement an Authentication Request Handler to Construct a GenericPrincipal Object

This procedure implements the Application_AuthenticateRequest event handler within global.asax and creates a GenericPrincipal object for the currently authenticated user. This will contain the list of groups that the user is a member of, retrieved from the FormsAuthenticationTicket contained in the authentication cookie. Finally, you will associate the GenericPrincipal object with the current HttpContext object that is created for each Web request.
To implement an authentication request handler to construct a GenericPrincipal object
  1. Use Solution Explorer to open global.asax.cs.
  2. Add the following using statements to the top of the file.
3.  using System.Web.Security;
4.  using System.Security.Principal;
  1. Locate the Application_AuthenticateRequest event handler and add the following code to obtain the cookie that contains the encrypted FormsAuthenticationTicket, from the cookie collection passed with the request.
6.  // Extract the forms authentication cookie
7.  string cookieName = FormsAuthentication.FormsCookieName;
8.  HttpCookie authCookie = Context.Request.Cookies[cookieName];
9.   
10.if(null == authCookie)
11.{
12.  // There is no authentication cookie.
13.  return;
14.} 
  1. Add the following code to extract and decrypt the FormsAuthenticationTicket from the cookie.
16.FormsAuthenticationTicket authTicket = null;
17.try
18.{
19.  authTicket = FormsAuthentication.Decrypt(authCookie.Value);
20.}
21.catch(Exception ex)
22.{
23.  // Log exception details (omitted for simplicity)
24.  return;
25.}
26. 
27.if (null == authTicket)
28.{
29.  // Cookie failed to decrypt.
30.  return; 
31.}
  1. Add the following code to parse out the pipe separate list of group names attached to the ticket when the user was originally authenticated.
33.// When the ticket was created, the UserData property was assigned a
34.// pipe delimited string of group names.
35.String[] groups = authTicket.UserData.Split(new char[]{'|'});
  1. Add the following code to create a GenericIdentity object with the user name obtained from the ticket name and a GenericPrincipal object that contains this identity together with the user's group list.
37.// Create an Identity object
38.GenericIdentity id = new GenericIdentity(authTicket.Name,
39.                                         "LdapAuthentication");
40. 
41.// This principal will flow throughout the request.
42.GenericPrincipal principal = new GenericPrincipal(id, groups);
43.// Attach the new principal object to the current HttpContext object
44.Context.User = principal;

Step 7. Test the Application

This procedure uses the Web application to request the default.aspx page. You will be redirected to the logon page for authentication. Upon successful authentication, your browser will be redirected to the originally requested default.aspx page. This will extract and display the list of groups that the authenticated user belongs to from the GenericPrincipal object that has been associated with the current request by the authentication process.
To test the application
  1. On the Build menu, click Build Solution.
  2. In Solution Explorer, right-click default.aspx, and then click View in Browser.
  3. Enter a valid domain name, user name, and password and then click Log On.
  4. If you are successfully authenticated, you should be redirected back to default.aspx. The code on this page should display the user name of the authenticated user.
To see the list of groups the authenticated user is a member of, add the following code at the end of the Application_AuthenticateRequest event handler in the global.aspx.cs file.
Response.Write("Groups: " + authTicket.UserData + "<br>");
 
http://msdn.microsoft.com/en-us/library/ff649227.aspx
 



WCF Services Security


WCF Security:

Two types of Security:

1.  Transport Security
2. Message Security       


Binding Types:

·        wsHttpBinding
·        netTcpBinding
·        basicHttpBinding
·        mexHttpBinding

Example for Transport Security:

<system.serviceModel>
    <services>
      <service name="CustomerService.CustomerService">
        <!-- 2 setepin WCF Service this is (https)-->
        <endpoint
                    address="https://localhost:42126/CustomerService.svc"
                    binding="wsHttpBinding"
                    contract="CustomerService.ICustomerService"   
                    bindingConfiguration="TransportSecurity"
                    name="BasicHttpBinding_ICustomerService" />
      
      
        <!--<endpoint
                    address="net.Tcp://http://localhost:42126/CustomerService.svc"
                    binding="netTcpBinding"
                    contract="CustomerService.ICustomerService"  
                    bindingConfiguration="BasicHttpBinding_ICustomerService"
                    name="BasicHttpBinding_ICustomerService" />-->

        <!-- Step 3 setep in WCF Service (this is mexHttpBinding)-->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" ></endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 4 setep WCF Service this is (httpsGetEnabled="True")-->
          <serviceMetadata httpsGetEnabled="True"/>        
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>     
      </serviceBehaviors>
    </behaviors>
 
    <bindings>
      <wsHttpBinding >
        <binding name="TransportSecurity">
          <!-- 1 setep WCF Service this is (mode="Transport")-->
          <security mode="Transport">         
            <transport clientCredentialType="None"></transport>
          </security>
        </binding>       
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>

After That, Host the service in IIS and create Certificate the SSL and add this certificate.




Web Service Config:
<system.serviceModel>

    <bindings>

      <wsHttpBinding>

        <binding name="wsHttpEndpointBinding">

          <security mode="Transport" >

            <message clientCredentialType="Certificate" />

          </security>

        </binding>

      </wsHttpBinding>

    </bindings>

    <services>

      <service name="WCFServiceCertificate.Service1" behaviorConfiguration="WCFServiceCertificate.Service1Behavior">

        <!-- Service Endpoints -->

        <endpoint address="https://www.mysite.com/Service.svc" listenUri="https://machinename.doman/Service.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">

          <!-- 

              Upon deployment, the following identity element should be removed or replaced to reflect the 

              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity 

              automatically.

          -->

          <!--<identity>

            <dns value="localhost"/>

          </identity>-->

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="WCFServiceCertificate.Service1Behavior">

          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

          <serviceMetadata httpsGetEnabled="true"/>

          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->

          <serviceDebug includeExceptionDetailInFaults="false"/>

          <serviceCredentials>

            <clientCertificate>

              <authentication certificateValidationMode="ChainTrust"/>

            </clientCertificate>

            <serviceCertificate findValue="RealCert"

                                storeLocation="LocalMachine"

                                storeName="TrustedPeople"

                                x509FindType="FindBySubjectName" />

          </serviceCredentials>

        </behavior>

      </serviceBehaviors>

    </behaviors>

  </system.serviceModel>


Web Client Config:
<system.serviceModel>

    <bindings>

      <wsHttpBinding>

        <binding name="WSHttpBinding_IService1" closeTimeout="00:01:00"

            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"

            bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"

            maxBufferPoolSize="524288" maxReceivedMessageSize="65536"

            messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"

            allowCookies="false">

          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"

              maxBytesPerRead="4096" maxNameTableCharCount="16384" />

          <reliableSession ordered="true" inactivityTimeout="00:10:00"

              enabled="false" />

          <security mode="Transport">

            <transport proxyCredentialType="None"/>

            <message clientCredentialType="Certificate" negotiateServiceCredential="true"

                algorithmSuite="Default" establishSecurityContext="true" />

          </security>

        </binding>

      </wsHttpBinding>

    </bindings>

    <client>

      <endpoint address="https://www.mysite.com/Service.svc" binding="wsHttpBinding"

          bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"

          name="WSHttpBinding_IService1" behaviorConfiguration="CustomBehavior">

      

      </endpoint>

    </client>

    <behaviors>

      <endpointBehaviors>

        <behavior name="CustomBehavior">

          <clientCredentials>

            <clientCertificate findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />

            <serviceCertificate>

              <authentication certificateValidationMode="ChainTrust"/>

            </serviceCertificate>

          </clientCredentials>

        </behavior>

      </endpointBehaviors>

    </behaviors>

  </system.serviceModel>

There are four core security features that WCF addresses:-

Confidentiality: This feature ensures that the information does not go in wrong hands when it travels from the sender to the receiver.

Integrity: This feature ensures that the receiver of the message gets the same information that the sender sends without any data tampering. 

Authentication: This feature verifies who the sender is and who the receiver is. 

Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.
 

When we talk about WCF security there are two aspects, the first is the data and the second is the medium on which the data travels i.e. the protocol. WCF has the ability to apply security at the transport level (i.e. protocol level) and also at message level (i.e. data).
 

Figure: - Transport and Message level security
 
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.

Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.
 
Note :- The below table is taken from book Pro WCF: Practical Microsoft SOA Implementation -- Chris peiris and Denis mulder – Apress 2007
Below is a table which shows for which binding which mode is supported. We did not discuss the mixed mode. It’s nothing but combination of transport and mixed mode. For instance data encrypted and passed over WsHttp using HTTPS is a mixed mode of security. Encryption is nothing but message security and HTTPS is a transport mode. In a combination they form mixed mode.
Binding
Transport Mode?
Message Mode?
Mixed Mode?
BasicHttpBinding
Yes
Yes
Yes
WsHttpBinding
Yes
Yes
Yes
WsDualHttpBinding
No
Yes
No
NetTcpBinding
Yes
Yes
Yes
NetNamedPipeBinding
Yes
No
No
NetMsmqBinding
Yes
Yes
No
MsmqIntegrationBinding
Yes
No
No



Transport
Message
Scenarios when we should be using one of them
When there are no intermediate systems in between this is the best methodology.  
If it’s an intranet type of solution this is most recommended methodology.
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.
Advantages
  • Does not need any extra coding as protocol inherent security is used.
  • Performance is better as we can use hardware accelerators to enhance performance.
  • There is lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.

  • Provides end to end security as it’s not dependent on protocol. Any intermediate hop in network does not affect the application.
  • Supports wide set of security options as it is not dependent on protocol. We can also implement custom security.
Disadvantages
  • As it’s a protocol implemented security so it works only point to point.
  • As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.
  • Needs application refactoring to implement security.
  • As every message is encrypted and signed there are performance issues.
  • Does not support interoperability with old ASMX webservices/

Figure: - Route paths
 
Let’s make a simple sample which will demonstrate how we can use transport security using WsHttp binding with HTTPS security.
 
Step 1:- Create a simple service using WCF project
 
The first step is to create a simple WCF project. So click on new project and select WCF service project. By default WCF project creates a default function ‘GetData()’. We will be using the same function for this sample.
 



http://www.codeproject.com/images/minus.gif Collapse | Copy Code
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Step 2 :- Enable transport level security in the web.config file of the service
 
Next step is to enable transport security in WsHttp binding. This is done using the ‘Security’ XML tag as shown in the below code snippet.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<bindings>
<wsHttpBinding>
<binding name="TransportSecurity">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
Step 3:- Tie up the binding and specify HTTPS configuration
 
We need now tie up the bindings with the end points. So use the ‘bindingConfiguration’ tag to specify the binding name. We also need to specify the address where the service is hosted. Please note the HTTS in the address tag.

Change ‘mexHttpBinding’ to ‘mexHttpsBinding’ in the second end point.
 



<service name="WCFWSHttps.Service1" behaviorConfiguration="WCFWSHttps.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="https://localhost/WCFWSHttps/Service1.svc" binding="wsHttpBinding" bindingConfiguration="TransportSecurity" contract="WCFWSHttps.IService1"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
In the ‘serviceMetadata’ we also need to change ‘httpGetEnabled’ to ‘httpsGetEnabled’.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<serviceBehaviors>
........
.........
<serviceMetadata httpsGetEnabled="true"/>
.........
.........
</serviceBehaviors>
Step 4:- Make the web application HTTPS enabled
 
Now that we are done with the WCF service project creation and the necessary configuration changes are done. It’s time to compile the WCF service project and host the same in IIS application with HTTPS enabled.

We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purpose. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.

You can get the same from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” or you can also get it from windows SDK.

You can type the below thing through your dos prompt on “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin”. Please note “compaq-jzp37md0” is the server name so you need to replace with your PC name.
 
 
makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
 
If you run the same through your command prompt you should get a succeeded message as shown below.

Now it’s time to assign this certificate to your IIS website. So go to IIS properties , click on directory security tab and you should see server certificate tab.


So click on the server certificate tab and you will then be walked through an IIS certificate wizard. Click ‘Assign a existing certificate’ from the wizard.

You can see a list of certificates. The “compaq-jzp37md0” certificate is the one which we just created using ‘makecert.exe’.

Now try to test the site without ‘https’ and you will get an error as shown below….That means your certificate is working.


Do not forget to enable IIS anonymous access.
 
Step 5:- Consume the service in a web application
 
It’s time to consume the service application in ASP.NET web. So click on add service reference and specify your service URL. You will shown a warning box as shown in the below figure. When we used makecert.exe we did not specify the host name as the service URL. So just let it go. 
 

Step 6:- Suppress the HTTPS errors
 
‘makecert.exe’ creates test certificates. In other words it’s not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we have created a function called as ‘IgnoreCertificateErrorHandler’ which return true even if there are errors. This function is attached as a callback to ‘ServicePointManager.ServerCertificateValidationCallback’.

In the same code you can also see service consuming code which calls the ‘GetData’ function.
 





http://www.codeproject.com/images/minus.gif Collapse | Copy Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplicationConsumer.ServiceReference1;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace WebApplicationConsumer
{
public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
Service1Client obj = new Service1Client();
Response.Write(obj.GetData(12));
}
public static bool IgnoreCertificateErrorHandler(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
}
Step 7:- Enjoy success
 
Now to the easiest step, compile you ASP.NET client and enjoy success.
http://www.codeproject.com/KB/WCF/WCFFAQPart3/10.jpg
Let’s do a simple example of message security using Wshttp with X509 certificates.
 
Step 1:- Create client and server certificates
 
Create two certificates one for the server and the other for the client using makecert.exe. You can get makecert.exe from “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin” folder. So you can goto dos prompt and run the below command snippet.
 
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WCfServer -sky exchange -pe
makecert.exe -sr CurrentUser -ss My -a sha1 -n CN=WcfClient -sky exchange -pe
 
Below is a detailed explanation of various attributes specified in the ‘makecert.exe’.
Attribute
Explanation
-sr
Specifies the registry location of the certificate store. The SubjectCertStoreLocation argument must be either of the following: 
currentUser
 
Specifies the registry location HKEY_CURRENT_USER.
 
localMachine
 
Specifies the registry location HKEY_LOCAL_MACHINE.
-ss
Specifies the name of the certificate store where the generated certificate is saved.
-a
Specifies the algorithm. Can be either MD5 or SHA1.
-n
Specifies a name for the certificate. This name must conform to the X.500 standard. The simplest method is to use the "CN=MyName" format.If the /n switch is not specified; the default name of the certificate is "Joe's Software Emporium".
-sky
Specifies how will be the key type. Can be either exchange or signature.
-pe
This makes the key exportable.

Note: - Makecert.exe is a free tool provided by Microsoft which helps to create X.509 certificate that is signed by a system test root key or by another specified key. This is a test certificate and not a real one and should not be used for production purpose. For production buy proper certificates from Thawte, Verisign, GeoTrust etc.
 
Currently we have specified that we want to create the client key with ‘WcfClient’ name and server key with ‘WCFServer’. The certificates should be created for the current user and should be exportable.


Once you run the command you should see the ‘Succeeded’ message as shown in the below figure. Below figure shows keys created for both server and client.

Step 2 :- Copy the certificates in trusted people certificates
 
Go to start à run and type MMC and press enter. You will be popped with the MMC console. Click on file à Add/remove snap-in. 
 

You will be popped up with a Add/Remove Snap-in , click on the add button , select certificates and select ‘My user Account’.
You can see the certificates created for client and server in the personal certificates folder. We need to copy those certificates in trusted people à certificates folder.
 
 

Step 3 :- Specify the certification path and mode in the WCF service web.config file
 
Now that we have created both the certificates we need to refer these certificates in our WCF project.
So we have created two projects one which has the WCF service and the other project is a web application which will consume the WCF service.

Let’s open the web.config file of the WCF service and enter two important things:-
• Where the certificate is stored, location and how WCF application should find the same. This is defined using ‘serviceCertificate’ tag as shown in the below snippet.
• The ‘certificationvalidationmode’ defines how client certificates will be authenticated.
 
Certification validation mode
Description
Chain trust
In this situation the client certificate is validated against the root certificate.
Peer trust
PeerTrust ensures that the public key portion of the certificate is in the Trusted People certificate folder on the clients computer
ChainORPeertrust
This is just a OR condition for both chain and peer.
The above two points is clubbed together and entered in the web.config file of the WCF service.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</clientCertificate>
<serviceCertificate findValue="WCfServer"
storeLocation="CurrentUser"
storeName="My"
x509FindType="FindBySubjectName" />
</serviceCredentials>
Step 4 :- Define bindings
 
Now that we have defined our certificates and authentication type we need to define that the authentication values will be sent through message using certificates. You can see we have defined the ‘WsHttpBinding’ with message attribute specifying that the WCF client needs to send a certificate for validation.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpointBinding">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
Step5 :- Tie up the bindings with end point
 
Once done we need to tie up this binding with the end point. This is done by using ‘bindingConfiguration’ tag as shown in the below code snippet.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<endpoint address="" binding="wsHttpBinding" "BACKGROUND-COLOR: #ffff00">bindingConfiguration"BACKGROUND-COLOR: #ffff00">="wsHttpEndpointBinding" contract="WCFServiceCertificate.IService1">
Step 6 :- Make your web application client for consuming the WCF service
 
That’s all we need to from the WCF service perspective. So compile the WCF service and reference the same in the ASP.NET web application using ‘Service reference’. Below is the code snippet where we have referenced the service and called the ‘GetData’ function of the service/ 
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
"BACKGROUND-COLOR: #ffff00">using WebConsumer.ServiceReference1;
namespace WebConsumer
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
"BACKGROUND-COLOR: #ffff00">Service1Client obj = new Service1Client();
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
"BACKGROUND-COLOR: #ffff00">Response.Write(obj.GetData(12));
}
}
}
Now if you try to run the client i.e. the web application as it is you should get an error as shown below. The error clearly indicates you can use the WCF service until you do not provide the client certificate.

Step 7 :- Define certificates in WCF client
 
So let’s start the process of defining certificates in the WCF client. The way we have defined authentication certification mode and the path of the certificate, in the same way we need to define it for WCF client. You can see we have defined the authentication mode as ‘peertrust’ and we have specified the client certificate name as ‘WcfClient’.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<behaviors>
<endpointBehaviors>
<behavior name="CustomBehavior">
<clientCredentials>
<clientCertificate findValue="WcfClient" x509FindType="FindBySubjectName" storeLocation="CurrentUser" storeName="My" />
<serviceCertificate>
<authentication certificateValidationMode="PeerTrust"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
Step 8 :- Tie up the behavior with end point on WCF client
 
We need to tie up the above defined behavior with the end point. You can see we have bounded the behavior using ‘behaviorConfiguration’ property. We also need to specify that the DNS value will be ‘WcfServer’ which your server certificate name.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<client>
<endpoint address="http://localhost:1387/Service1.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService1"
"BACKGROUND-COLOR: #ffff00">behaviorConfiguration="CustomBehavior">
<identity>
"BACKGROUND-COLOR: #ffff00"><dns value="WcfServer" />
</identity>
</endpoint>
</client>




Step 9 :- Enjoy your hard work
 
Once we are done you can run the ASP.NET web and you should see the below display.

If we want to summarize in one sentence the difference between ‘WsHttpBinding’ and ‘BasicHttpBinding’ is tha ‘WsHttpBinding’ supports ‘WS-*’ specification. WS-* specifications are nothing but standards to extend web service capabilities.

Below is a detailed comparison table between both the entities from security, compatibility, reliability and SOAP version perspective.
Criteria
BasicHttpBinding
WsHttpBinding
Security support
This supports the old ASMX style i.e WS-BasicProfile 1.1.
This exposes web services using WS-* specifications.
Compatibility
This is aimed for clients who do not have .Net 3.0 installed and it supports wider ranges of client. Many of clients like Windows 2000 still do not run .NET 3.0. So older version of .NET can consume this service.
As its built using WS-* specifications it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.
Soap version
SOAP 1.1
SOAP 1.2 and WS-Addressing specification.
Reliable messaging
Not supported. In other words if a client fires two or three calls you really do not know they will return back in the same order.
Supported as it supports WS-* specifications.
Default security options
By default there is not security provided for messages when the client calls happen. In other words data is sent as plain text.
As WsHttBinding supports WS-* it has WS-Security enabled by default. So the data is not sent in plain text.
Security options
  • None
  • Windows – default authentication.
  • Basic
  • Certificate
  • None
  • Transport.
  • Message.
  • Transport with message credentials.
One of the biggest differences you must have noticed is the security aspect. By default ‘BasicHttpBinding’ sends data in plain text while ‘WsHttpBinding’ sends in encrypted and secured manner. To demonstrate the same let’s make two services one using ‘BasicHttpBinding’ and the other using ‘WsHttpBinding’ and then let’s see the security aspect in a more detailed manner.

We will do a small sample to see how ‘BasicHttpBinding’ sends data in plain text format and how ‘WsHttpBinding’ encrypts data.
 
Note :- By Default security is not enabled on ‘BasicHttpBinding’ for interoperability purpose. In other words it like our old webservice i.e. ASMX. But that does not mean we cannot enable security in ‘BasicHttpBinding’. Sometimes back we had a written a article on how to enable security on ‘BasicHttpBinding’WCFBasicHttpBinding.aspx 
 
In order to understand the security differences between both these entities we will do a small project. In this project we will create two WCF service one service using ‘BasicHttpBinding’ and the second service using ‘WsHttpBinding’. 
 

Step1:- So let’s first create a simple service using ‘BasicHttpBinding’. For that we just a create a simple WCF project and then modify the ‘ServiceModel’ element as shown below. You can see in the ‘endpoint’ tag we have specified ‘basicHttpBinding’ as the protocol.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<system.serviceModel>
<services>
<service name="WCFBasicHttpBinding.Service1" behaviorConfiguration="WCFBasicHttpBinding.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="WCFBasicHttpBinding.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>

</system.serviceModel>
Step 2 :- We also need to create one more service using ‘WsHttpBinding’. For that you do not need to anything special as such. By default WCF project is created using ‘WsHttpBinding’. Below is how the Web.config file looks like. You can see how the endpoint tag is using ‘wsHttpBinding’.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<system.serviceModel>
<services>
<service name="WCFWsHttpBindingHttps.Service1" behaviorConfiguration="WCFWsHttpBindingHttps.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="WCFWsHttpBindingHttps.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWsHttpBindingHttps.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>


</system.serviceModel>
Step 3 :- We will not be creating any new methods in both the services. We will just use the default code created by the WCF template. So both these services will have a ‘GetData’ function which returns a string. The ‘GetData’ function is a default function created WCF project.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Step 4 :- Now that out services are created we need to create a client which will consume this service. So we have created a simple web application and we have added two references one is a service reference i.e. ‘WsHttpBinding’ and the second is a web reference i.e. ‘BasicHttpBinding’. Please note when you right click to add reference you need to use the ‘Add service reference’ to add ‘WsHttpService’ and you need to add web reference for ‘BasicHttpBinding’.
http://www.codeproject.com/KB/WCF/WCFFAQPart3/18.jpg
We will add two buttons on the default aspx page. One button will call the http service and the other will call the wshttp service. Below is how the function ‘GetData’ is called in both the button clicks.

Step 5 :- So now we are ready with the complete project it is time to sniff and see how data is transported between client and the service in both the scenarios. So let’s download a simple http data recorder fromhttp://www.ieinspector.com/httpanalyzer/download.html  . We will then click both the buttons one by one and record the data transfer using httpanalyzer. You can see the posted data is in simple plain XML format for basic http protocol and it’s in an encrypted format for wshttp protocol.

If you are looking for back ward compatibility and to support lot of clients then basic http binding is the way to go or else WsHttp is the great way to start if you are seeing your clients made in .NET 3.0 and above.
 
Step 1:- Create a project of WCF service application as shown in the below figure.

Circle WCF service application àSelect this 
 
By default the WCF project creates a class file which has ‘GetData’ function. This function takes in a number values and displays a explanatory sentence like ‘You entered 1 value’ , in case you have entered ‘1’.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
Step 2:- When we create a WCF service application it also has a web.config file associated with it. So open the web.config file and ensure that authentication mode is windows.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<authentication mode="Windows" />
Step 3:- The third step is to define the bindings and the transport type. To define the bindings we need to enter ‘basicHttpBinding’ element inside the ‘bindings’ XML tag. We also need to define the ‘clientCredentialType’ as windows.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
.........
.........
</system.serviceModel>
Step 4:- Now the bindings defined needs to be associated with service interface i.e. ‘service1’. So we need to modify the services elements as shown below. You can note that we have defined a end point which has the binding association.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<system.serviceModel>
........
........
........
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
.........
.........
.........
.........
</system.serviceModel>
So over all your <system.serviceModel> XML part as whole with bindings and services is a shown below.
 
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>






Step 5 :- Go to IIS properties and click on security tab and ensure that anonymous access is disabled and only windows authentication is enabled.


Step 6:- We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication.

Step 7:- So let’s consume this WCF services. So add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.

Step 8:- Type in the following code snippet in your page load. So add the namespace reference and call the method ‘GetData’. The most important step to note is the credential supplied. ‘DefaultCredentials’ passes the current windows identity to the WCF service.

If you execute the service you should get the following display as shown below.

You can try commenting the below code in your client in other words we are not passing any credentials.