Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / IIS

Authentication in web services using C# and Kerberos (POC)

4.81/5 (20 votes)
9 Sep 2008CPOL7 min read 1  
This is a proof of concept article (POC) to explain how the Kerberos authentication can be implemented to authenticate users when they need to request a web service.

Introduction

This article is a proof of concept article (POC). It explains how the Kerberos authentication can be implemented to authenticate users when they need to request a web service using WSE 3.0. This goal is very important, especially when using the Service Oriented Architecture (SOA). I decided to write this article after reading one of the Microsoft patterns and practices: Web Service Security Guide, which is a very good reference in this issue.

The following article doesn't describe how the Kerberos authentication works, in detail, and supposes that the reader has a good idea about it. It focuses on how to implement it using Microsoft technologies. A single sign on (SSO) implementation is the main usage of this concept. For example: suppose we have two domain users, a marketing group user and an accounting group user. Each one can login to his Windows account and then open the company website without any need to be authenticated against the company website. Sign on is done once when logging to Windows. And, the company website, for sure, gives each user his group privileges only. Simply put, we have the following participants in our system:

  • Web service: that authenticates any client that needs to request it.
  • Client: that needs to request the web service; it should provide the credentials for authentication when requesting the web service.
  • Kerberos Distribution Center (KDC): it is responsible for authenticating the client and issuing a ticket that has the client credential, and then the client can use it for authentication with the web service. For the Microsoft environment, KDC is available in Windows Server 2003, for example, which is a domain controller.

Image 1

The above figure shows the relationship between our system participants. Now, let's divide our article into two parts:

  • Part I: The basic knowledge that is required to implement our demo. It could be illustrated in the following points:
    • Overview of the Kerberos authentication process.
    • Preparing web services and IIS configuration.
    • Applying the Kerberos authentication on web services.
    • Applying the Kerberos authentication on the client application.
  • Part II: Describes a very simple demo based on part I.

Part I:

Overview of the Kerberos authentication process

Briefly, when a client needs to request a service, it does five steps, as shown in the following diagram:

Image 2

I want to explain more about steps 2 and 4.

  • In step 2, the KDC does the following:
    • Generates a new key for the session, called the session key.
    • Packaged the newly generated session key and some client data in a service ticket.
    • Encrypts the service ticket with the web service master key (known by the web service).
    • Sends the encrypted service ticket and the new session key to the client.

    Then, the client doed the following:

    • Uses the session key to encrypt the authenticator (contains a time stamp and other information).
    • Packages the encrypted authenticator and the service ticket in a new Kerberos security token.
  • In step 4, the web service does the following:
    • Gets the service ticket from the Kerberos token.
    • Uses its master key to decrypt it.
    • Gets the session key from the decrypted service ticket.
    • Uses the session key to decrypt the authenticator and validate the text.

Preparing web services and IIS configuration

In this section, we will learn more about the master key and how to have a web service with a unique master key. What is a master key that is used to encrypt the service ticket? In a Windows server: each registered object (computer or user) on the KDC has a shared key (also called master key). This shared key is used for encrypting the service ticket and also for decrypting it. The object is registered on the KDC by a unique name called SPN (Service Principal Name), so when requesting a ticket from the KDC, the SPN should be determined. By default, all services running on Windows use the built-in account Network Service, and the default SPN that refers to it ‘host/PCName’. The default application pool on IIS uses the Network Service account to identify itself to Windows. That means, when a service ticket is generated to a web service on IIS, it is encrypted by the shared key that is related to the ‘Network Service’ account, and then any web service that uses the same application pool can decrypt the ticket.

To dedicate a web service to a new master key, you need to do the following:

  1. Add a new domain account to the Active Directory.
  2. Create a new SPN that refers to the new domain account.
  3. Add a new application pool on IIS, and map its identity to the new domain account.
  4. Configure the web service virtual directory to use the new application pool.
  5. Grant the new account all permission needed to access the web service virtual directory and to work as an IIS_WPG group.
  6. Restart IIS.

Details:

Create a new SPN that refers to the new domain account:

The Setspn tool is included in the Windows Support Tools, and is used for managing SPNs.

Image 3

Type the following command in the command prompt: Setspn –a http/ServiceName DomainName\DomainAccount, where:

  • ServiceName: is the name of the web service.
  • DomainName: is the name of the domain.
  • DomainAccount: is the new domain account name.

Image 4

Add a new application pool on IIS, and map its identity to the new domain account:

Image 5

Image 6

Image 7

Image 8

Configure the web service virtual directory to use the new application pool:

Image 9

Image 10

Grant the new account all permission needed to access the web service virtual directory and work as an IIS_WPG group:
  • Adding a new domain account to the IIS_WPG group.
  • Assign this new domain account the following two user rights to start the CGI processes: Adjust memory quotas for a process, and Replace a process level token.

Image 11

Image 12

Image 13

Image 14

  • Grant the new domain account full control on the web service folder.
  • Grant the new domain account full control on the temp folder in the Windows directory.

Applying Kerberos authentication on web services

To use Kerberos authentication in the web service:

  1. Enable WSE 3.0, and enable Policy.
  2. Add the Policy file and configure the Policy.
  3. Apply the Policy on the web service.

Details:

  1. Enable WSE 3.0, and enable Policy: by adding the following tags in the web.config file:
    XML
    <configSections>
      <section name="microsoft.web.services3" 
        type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration,
             Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, 
             PublicKeyToken=31bf3856ad364e35" />
    </configSections>
    
    <system.web>
    
      <compilation debug="true">
        <assemblies>
          <add assembly="Microsoft.Web.Services3, Version=3.0.0.0,
    Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </assemblies>
      </compilation>
    
      <webServices>
        <soapExtensionImporterTypes>
          <add type="Microsoft.Web.Services3.Description.WseExtensionImporter,
                        Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, 
                        PublicKeyToken=31bf3856ad364e35" />
        </soapExtensionImporterTypes>
        <soapServerProtocolFactory 
          type="Microsoft.Web.Services3.WseProtocolFactory,Microsoft.Web.Services3,
                Version=3.0.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </webServices>
    </system.web>
    
    <microsoft.web.services3>
      <policy fileName="wse3policyCache.config" />
      <tokenIssuer>
        <statefulSecurityContextToken enabled="false" />
      </tokenIssuer>
    </microsoft.web.services3>
  2. Add the Policy file and configure the Policy: add a config file to your project, name it ‘wse3policyCache.config’, then add the following tags to it:
    XML
    <policies xmlns="http://schemas.microsoft.com/wse/2005/06/policy">
      <policy name="KerberosService">
        <authorization>
          <allow user="Mawhiba\Akram" />
          <deny role="*" />
        </authorization>
        <kerberosSecurity establishSecurityContext="true"
        renewExpiredSecurityContext="true" requireSignatureConfirmation="false"
        messageProtectionOrder="SignBeforeEncryptAndEncryptSignature"
        requireDerivedKeys="true" ttlInSeconds="300">
          <protection>
            <request 
               signatureOptions="IncludeAddressing, IncludeTimestamp, 
                                 IncludeSoapBody" 
               encryptBody="true" />
            <response signatureOptions="IncludeAddressing, IncludeTimestamp, 
                                        IncludeSoapBody" 
                      encryptBody="true" />
            <fault signatureOptions="IncludeAddressing, IncludeTimestamp, 
                                     IncludeSoapBody" 
                   encryptBody="false" />
          </protection>
        </kerberosSecurity>
        <requireActionHeader />
      </policy>
    </policies>

    The authorization part may be changed according to the business roles.

  3. Apply the policy on the web service: by adding the following code before the service class:
    C#
    [Policy("KerberosService")]

Applying Kerberos authentication on the client application

To use Kerberos authentication in the client:

  1. Enable WSE 3.0, and enable Policy.
  2. Add the Policy file and configure the Policy.
  3. Use the enhanced version of the web service and apply the Policy on the client.

Details:

  1. Enable WSE 3.0, and enable the Policy: by adding the following tags in the web.config file:
    XML
    <configSections>
      <section name="microsoft.web.services3" 
         type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration,
                Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, 
                PublicKeyToken=31bf3856ad364e35" />
    </configSections>
    
    <system.web>
    
      <compilation debug="true">
        <assemblies>
          <add assembly="Microsoft.Web.Services3, Version=3.0.0.0,
    Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        </assemblies>
      </compilation>
    
      <webServices>
        <soapExtensionImporterTypes>
          <add type="Microsoft.Web.Services3.Description.WseExtensionImporter,
                        Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, 
                        PublicKeyToken=31bf3856ad364e35" />
        </soapExtensionImporterTypes>
      </webServices>
    </system.web>
    
    <microsoft.web.services3>
      <policy fileName="wse3policyCache.config" />
    </microsoft.web.services3>
  2. Add the Policy file and configure the Policy: by adding a config file to your project, naming it ‘wse3policyCache.config’, then adding the following tags to it:
    XML
    <policies xmlns="http://schemas.microsoft.com/wse/2005/06/policy">
      <policy name="KerberosClient">
        <kerberosSecurity establishSecurityContext="true"
        renewExpiredSecurityContext="true" requireSignatureConfirmation="false"
        messageProtectionOrder="SignBeforeEncryptAndEncryptSignature"
        requireDerivedKeys="true" ttlInSeconds="300">
          <token>
            <kerberos targetPrincipal="http/ServiceName"
            impersonationLevel="Impersonation" />
          </token>
          <protection>
            <request 
              signatureOptions="IncludeAddressing, 
                                IncludeTimestamp, IncludeSoapBody" 
              encryptBody="true" />
            <response signatureOptions="IncludeAddressing, 
                                        IncludeTimestamp, IncludeSoapBody" 
               encryptBody="true" />
            <fault signatureOptions="IncludeAddressing, 
                                     IncludeTimestamp, IncludeSoapBody" 
               encryptBody="false" />
          </protection>
        </kerberosSecurity>
        <requireActionHeader />
      </policy>
    </policies>

    where ‘http/ServiceName’ is the SPN of the required service

  3. Use the enhanced version of the web service and apply the policy on the client: using the ‘Wse’ version, like in the following code:
    C#
    Client.localhost.ServiceWse myService = new ServiceWse(); 
    myService.SetPolicy("KerberosClient");

Part II:

Fine, we can now start our simple project to demonstrate Kerberos authentication:

  1. Create two web services with different master keys (webservice1 and webservice2).
  2. Apply Kerberos authentication, and add policies on each web service that allow a user and deny the others.
    XML
    <authorization>
      <allow user="CodeProject\Akram" />
      <deny role="*" />
    </authorization>
  3. In the two web services, write a test method like this:
    C#
    [WebMethod]
    public string Test()
    {
        return "Succeeded ";
    }
    
  4. Create a console application and add two references to the web services.
  5. Apply both Kerberos authentication policies on it (one policy to request webservice1 called 'KerberosClient1', and another to request webservice2 called ' KerberosClient2'). The policy file will be some thing like this:
    XML
    <policies xmlns="http://schemas.microsoft.com/wse/2005/06/policy">
      <policy name="KerberosClient1">
        <kerberosSecurity establishSecurityContext="true"
        renewExpiredSecurityContext="true" requireSignatureConfirmation="false"
        messageProtectionOrder="SignBeforeEncryptAndEncryptSignature"
        requireDerivedKeys="true" ttlInSeconds="300">
          <token>
            <kerberos targetPrincipal="http/WS1"
            impersonationLevel="Impersonation" />
          </token>
          <protection>
            <request signatureOptions="IncludeAddressing, 
                                       IncludeTimestamp, IncludeSoapBody" 
                     encryptBody="true" />
            <response signatureOptions="IncludeAddressing, 
                                        IncludeTimestamp, IncludeSoapBody" 
                      encryptBody="true" />
            <fault signatureOptions="IncludeAddressing, 
                                     IncludeTimestamp, IncludeSoapBody" 
                   encryptBody="false" />
          </protection>
        </kerberosSecurity>
        <requireActionHeader />
      </policy>
    
      <policy name="KerberosClient2">
        <kerberosSecurity establishSecurityContext="true"
        renewExpiredSecurityContext="true" requireSignatureConfirmation="false"
        messageProtectionOrder="SignBeforeEncryptAndEncryptSignature"
        requireDerivedKeys="true" ttlInSeconds="300">
          <token>
            <kerberos targetPrincipal="http/WS2"
            impersonationLevel="Impersonation" />
          </token>
          <protection>
            <request signatureOptions="IncludeAddressing, 
                                       IncludeTimestamp, IncludeSoapBody" 
                     encryptBody="true" />
            <response signatureOptions="IncludeAddressing, 
                                        IncludeTimestamp, IncludeSoapBody" 
                      encryptBody="true" />
            <fault signatureOptions="IncludeAddressing, 
                                     IncludeTimestamp, IncludeSoapBody" 
                   encryptBody="false" />
          </protection>
        </kerberosSecurity>
        <requireActionHeader />
      </policy>
    </policies>

    We don't have a web.config in this console application, so we can use the app.config file to enable WSE. The App.config, after modification and adding the web references, will be some thing like this:

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="microsoft.web.services3" 
          type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration,
                Microsoft.Web.Services3,Version=3.0.0.0, Culture=neutral, 
                PublicKeyToken=31bf3856ad364e35" />
        <sectionGroup name="applicationSettings" 
                type="System.Configuration.ApplicationSettingsGroup, System, 
                      Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
          <section name="Client.Properties.Settings" 
                type="System.Configuration.ClientSettingsSection, System, 
                      Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                requirePermission="false" />
        </sectionGroup>
      </configSections>
      <microsoft.web.services3>
        <policy fileName="wse3policyCache.config" />
      </microsoft.web.services3>
      <applicationsettings />
        <client.properties.settings />
          <setting name="Client_localhost_Service" serializeAs="String">
            <value />http://localhost/WS_Kerb_Demo/Service.asmx</value>
          </setting>
          <setting name="Client_localhost2_Service" serializeAs="String">
            <value>http://localhost/WS_Kerb_Demo2/Service.asmx</value>
          </setting>
        </Client.Properties.Settings>
      </applicationSettings>
    </configuration>
  6. Write some code trying to request the two web services using the two policies, like that:
    C#
    class Program
    {
        static void Main(string[] args)
        {
            localhost1.ServiceWse service1 = new localhost1.ServiceWse();
            localhost2.ServiceWse service2 = new localhost2.ServiceWse();
    
            service1.SetPolicy("KerberosClient1");            
    
            Console.WriteLine("");
            Console.WriteLine("(1) Token with first SPN " + 
                              "and calling the first service ");
    
            try
            {
                Console.WriteLine(service1.Test());
            }
            catch
            {
                Console.WriteLine("Failed");
            }
            Console.ReadLine();
    
            Console.WriteLine("");
    
            service2.SetPolicy("KerberosClient1");
            Console.WriteLine("(2) Token with first SPN " + 
                              "and calling the secound service ");
    
            try
            {
                Console.WriteLine(service2.Test());
            }
            catch
            {
                Console.WriteLine("Failed ");
            }
            Console.ReadLine();
    
            Console.WriteLine("");
    
            service1.SetPolicy("KerberosClient2"); 
            Console.WriteLine("(3) Token with secound SPN" + 
                              " and calling the first service ");
    
            try
            {
                Console.WriteLine(service1.Test());
            }
            catch
            {
                Console.WriteLine("Failed ");
            }
            Console.ReadLine();
    
            Console.WriteLine("");
    
            service2.SetPolicy("KerberosClient2");
            Console.WriteLine("(4) Token with secound SPN" + 
                              " and calling the secound service ");
    
            try
            {
                Console.WriteLine(service2.Test());
            }
            catch
            {
                Console.WriteLine("Failed ");
            }
            Console.ReadLine();
            
        }
    }
  7. Run the application and you will see the following output:

OutPut.JPG

Thanks

I hope this article would be useful for some one. It is my first article on The Code Project, and I hope it is not the last. Finally, I would like to thank Arabian Advanced Systems (AAS) located in Riyadh – KSA, from where I got a lot of the article knowledge, for their support and team cooperation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)