asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Kerberos Authentication with Web Services Enhancements 2.0 -- Cont'd
By Chris Peiris


  • email this article to a colleague
  • suggest an article

    Kerberos Sample Application


    You will build three C# projects to illustrate Kerberos authentication. The security smarts of the projects will be accumulated in a class library project called "KerbAuth". The most common implementation of security is a dedicated security DLL that is invoked by the client application; therefore, you will build a Windows application called "TestKerberosApp" that will reference the KerbAuth DLL and invoke its methods. The Kerberos token is issued by the Key Distribution Centre (KDC) of the domain controller. The domain controller will live on the server farm. The client needs to communicate to the server farm over the wire; therefore, you need to build a server component that lives on the server farm. Service Oriented Architecture dictates having a Web service to receive the client calls; therefore, you are building a Web service called "TestGateway". The objective of the sample application is to illustrate the following.

    • The client will obtain a Kerberos Token from the KDC.
    • The Kerberos token will be added to the SOAP header using WSE 2.0
    • The SOAP envelope will be encrypted with the Kerberos token
    • The SOAP call (with Kerberos token) will be passed to the TestGateway Server.
    • The TestGateway server will decrypt the SOAP envelope and extract the Kerberos token.
    • The TestGateway will return the current logged on user and the roles of the user
    • A separate web method (example : isRole method) is used to embed the Kerberos token. This will have no encryption. This is to compare the sizes of the SOAP envelopes.
    • You will also use WSE 2.0 diagnostics tools to observer the incoming and outgoing SOAP envelopes.
    • You will not be signing SOAP envelopes in our example. The code is very similar to the encryption code. Please refer to the WSE documentation for further details)

    The KerbAuth and TestKerberosApp projects will be client side. The TestGateway project will be server side.

    Technologies leveraged to implement the sample.

    • WSE 2.0 : (Note : Install WSE as the "Visual Studio .NET Developer" profile.)
    • Visual Studio .NET 2003 with .NET Framework 1.1
    • Windows XP with service pack 1.

    Note: The XP workstation needs to be connected to a domain with Active Directory (AD) support. The XP workstation will ask for a Kerberos token by utilizing the WSE 2.0 code. The domain controller is responsible for creating a Kerberos token with the help of Active Directory. Therefore please make sure your domain has Windows 2000 or Windows 2003 domain controller with AD support. Unfortunately Windows NT 4.0 Server domain will not support Kerberos tokens.

    1. Create a new blank solution (File |New | Blank Solution)
    2. Name the solution "TestKerbAuth" and browse to a location where you like the code to reside. (Your screen should be similar to Figure 1.1). Add three new projects to the solution. Right click on the "TestKerbAuth" and select "Add" then "Add new Project". All code will be written in C#.

      Figure 1.1: Blank solution for applications

    3. Create a "Class Library" project. Name it "KerbAuth" and select an appropriate location for the code to reside. This is the DLL that the security logic is encapsulated.
    4. Create a "Windows Application" project. Name it "TestKerberosApp". This is the client application that confronts the user. Make this the default start up application of the solution. (Right click on "TestKerberosApp" and select "Set as Start-up Project") Create "ASP.NET web application" that acts as the "gateway" to the backend systems. Name this "TestGateway". After adding all these 3 projects your solution explorer should look similar to Figure 1.2

    Figure 1.2: Solution explorer with all projects.

    You will first learn how to build the "TestGateway" to receive the Kerberos token. Then you will concentrate on building the clients to invoke the Web service.

    Web Service to Receive Kerberos Tokens.

    The WSE 2.0 must be installed before you code the TestGateway Web services. Here are the steps to configure WSE 2.0 on the Web services.

    1. Add WSE 2.0 to TestGateway. Right click on "TestGateway" and select "WSE Settings 2.0". You will view an image similar to Figure 1.3.

      Figure 1.3: Adding WSE 2.0 to TestGateway

    2. You will be presented with figure 1.4 when you click on the option. WSE 2.0 comes with a Visual Studio .Net plug-in for seamless integration into code. You are using this utility to configure WSE 2.0. For this exercise You will use two features of WSE 2.0. You will initially enable WSE 2.0, and then you will add the "tracing" ability to track our SOAP calls.
    3. The WSE 2.0 can be enabled by ticking the checkboxes of the plug-in dialog box. The interface is similar to figure 1.4. Please make sure that you select the "General" tab.

      Figure 1.4: Enabling WSE 2.0

      Please click the "Enable the project for Web Services Enhancements" checkbox. Adding this will do the following changes to your code.

      a) Add a reference to "microsoft.web.services2" DLL to the TestGateway" project. This will give access to the WSE functionality.
      b) The following code fragment will be added to the web.config file of TestGateway project.

    <configSections>

        <sectionname="microsoft.web.services2"type="Microsoft.Web.Services2.Configuration.WebServicesConfiguration, Microsoft.Web.Services2, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      </configSections>

    This will inform VS.NET of the configuration of WSE 2.0. This configuration handler will be used when the proxy objects are derived from TestGateway.

    You can also enable SOAP extensions for other protocols (non HTTP). It can be enabled by ticking the "Enable Microsoft Web Services Enhancements SOAP extensions" checkbox on figure 1.4. This will add the following line to the web.config file of TestGateway. You will use SOAP in the example. It is also important to note that this is only available on ASP.NET Web services projects. (This is not utilized in the sample application. However, it is an important configuration setting for non HTTP projects)

        <webServices>

          <soapExtensionTypes>

            <addtype="Microsoft.Web.Services2.WebServicesExtension, Microsoft.Web.Services2,Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"priority="1"group="0"/>

          </soapExtensionTypes>

        </webServices>

    The final configuration modification is to enable tracing. This can be achieved by utilizing the WSE 2.0 VS .NET plug-in. Navigate to the "Diagnostics" tab. You can tick the "Enabling Messaging Trace" checkbox. Please specify locations for the "input" and "output" files. The input file stores the incoming SOAP requests to the TestGateway server. The output file is the storage location for the respond SOAP calls from the TestGateway. The screen should be similar to figure 1.5

    Figure 1.5: Enabling tracing on TestGateway.

    Now you are ready to write some code. Here are the steps.

    1. Rename Services1.asmx to TestService.asmx
    2. You need to add some namespaces to help us with code. Please add the following namespaces at the top of the class.

    using Microsoft.Web.Services2;

    using Microsoft.Web.Services2.Security;

    using Microsoft.Web.Services2.Security.Tokens;

    You will write two web methods in this Web service. The first one is "GetName()". This method will return the username of the currently logged on user. The username will follow the "Domain\User name" format. I have also used this method to illustrate encryption of the SOAP envelope with the Kerberos token. Here is the code

    [WebMethod]

    publicstring GetName()

    {

         SoapContext requestContext = RequestSoapContext.Current;

         if (requestContext == null)

           thrownew ApplicationException("Only SOAP requests are permitted.");

         KerberosToken token = GetEncryptingToken(RequestSoapContext.Current) as KerberosToken;

         if (token == null)

         {

           thrownew SecurityFault(SecurityFault.FailedCheckMessage, SecurityFault.FailedCheckCode);

         }

         return token.Principal.Identity.Name.ToString();

    }

     

    First get the SOAP context by using "RequestSoapContext.Current". Then check whether the request context is a valid SOAP context. An application exception is raised if the SOAP context is not found. Therefore, you restrict users to use SOAP as their transport protocol. Then use the "GetEncryptingToken" function to get the encrypted token. Remember that the SOAP envelope is already encrypted with the Kerberos token. (This will be discussed later in the KerbAuth class library project) You will also throw an exception if you can't obtain the token. Finally use the "Principal.Identity.Name.ToString()" method to extract the user name from the Kerberos token. Look at the GeEncryptingToken function that extracts the encrypted token. This function will query the SOAP envelope for encryption data and return the Kerberos token to the caller.

    publicstatic SecurityToken GetEncryptingToken(SoapContext context)

    {

       foreach (ISecurityElement element in context.Security.Elements)

       {

         if (element is EncryptedData)

    {

           EncryptedData encryptedData = element as EncryptedData;

           System.Xml.XmlElement targetElement = encryptedData.TargetElement;                                                             

           if ( SoapEnvelope.IsSoapBody(targetElement))

             {

              return encryptedData.SecurityToken;

              }

         }

    }

    The isRole(string role) Web method is similar to GetName(). However, the isRole Web method is not encrypted with the Kerberos token. Therefore, you do not need to obtain the encrypted token. You can just navigate through the token collection of the context and obtain the security token. This is done by the "GetSecurityToken" method. You will use the Principal.IsInRole(role) method to check the roles of the logged on user. This function is very useful for role based security function calls.

    [WebMethod]

    publicbool isRole(string role)

    {

        SoapContext requestContext = RequestSoapContext.Current;

        if (requestContext == null)

          thrownew ApplicationException("Only SOAP requests are permitted.");

     

        token = GetSecurityToken(requestContext);

        return token.Principal.IsInRole(role);

    }

     

    private KerberosToken GetSecurityToken(SoapContext requestContext)

    {

      KerberosToken token = null;

      foreach (SecurityToken secToken in requestContext.Security.Tokens)

      {

        if (secToken is KerberosToken)

         token = (KerberosToken)secToken;

      }

      return token;

    }

    Now the code for the Web service is complete. Please build the project and make sure there are no errors. It's now time to concentrate on the clients.

    Developing the client to send Kerberos requests.

    The client code base consists of two projects. The "KerbAuth" DLL will hold the security logic of the application. You will build the "TestKerberosApp" Windows application to use the KerbAuth DLL to request Kerberos token and display the results. Build the KerbAuth DLL first.

    1. Navigate to the "KerbAuth" project
    2. Add a Web reference to the TestGateway (right click on the project and choose "Add Web Reference").
    3. Type in the URL of the Web services. Use http://localhost/TestGateway/TestService.asmx. Name the Proxy object "Proxy" and click the "Add Reference" button to generate a proxy object. Your screen should be similar the following image

      Figure 1.6 : Adding a web reference.

      It is interesting to look at the proxy WSE 2.0 generates. If you look into the Reference.cs file of the project you will see two instances of the TestService class (References.cs can be found under Reference.map file. It is found under the Proxy web reference. You may need to enable "view hidden files" to view this in solution explorer). As you can recall there is one instance of TestService class in the TestGateway Web service; however, there is a separate instance for WSE 2.0 calls (TestServiceWse) and a separate one for non WSE calls (TestService) in the proxy object. The code will be similar to this. Also notice that they inherit from different base classes.

          public class TestServiceWse : Microsoft.Web.Services2.WebServicesClientProtocol {

                      public TestServiceWse() {

                  this.Url = "http://localhost/TestGateway/TestService.asmx";

              }

      ……………………….

      ………………………

      public class TestService : System.Web.Services.Protocols.SoapHttpClientProtocol {

             

              public TestService() {

                  this.Url = "http://localhost/TestGateway/TestService.asmx";

              }

      The two instances of the TestService was automatically created by the proxy object creation. This will give you the choice to use or discard WSE 2.0, depending on the business requirements.

    4. Rename Class1.cs to KerberosHandler.cs and code the class. The source code can be found in the download file. There will be 2 functions to pass the details to the Web service. They are GetUser and isRole, but look at the GetName function first

    public string GetUser()

    {

      string targetPrincipalName = null;

      targetPrincipalName = "host/" + System.Net.Dns.GetHostName();

      KerberosToken kerbToken = new KerberosToken(targetPrincipalName);               

      if (kerbToken == null)

        throw new ApplicationException( "Unable to obtain security token." );

      KerbProxy = new Proxy.TestServiceWse();    KerbProxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60       KerbProxy.RequestSoapContext.Security.Tokens.Add(kerbToken);

      // Encrypt the SOAP body

      KerbProxy.RequestSoapContext.Security.Elements.Add( new  EncryptedData( kerbToken ) );

      return KerbProxy.GetName();

    }

    You need to know where the Key Distribution Centre (KDC) lies for Kerberos. This is obtained by utilizing the System.Net.Dns.GetHostName function. Then a Kerberos token is requested from the KDC. The next step is to create a proxy object and set the life time of the token. The life time of the Kerberos token is defined by the Security.Timestamp.TtlInSeconds property. Then add the token to the security token collection of the proxy object. Now instruct the SOAP context to encrypt the transport with the token credentials. Finally invoke the GetName method of the Web service. The request will have a Kerberos token embedded in it and the SOAP envelope will be encrypted with the token credentials. The isRole function is similar to GetUser function. However, it does not have encryption built in. Here is the code.

    public bool isRole(string role)

    {

      string targetPrincipalName = null;

      targetPrincipalName = "host/" + System.Net.Dns.GetHostName();

      KerberosToken kerbToken = new KerberosToken(targetPrincipalName);               

      if (kerbToken == null)

        throw new ApplicationException( "Unable to obtain security token." );

      KerbProxy = new Proxy.TestServiceWse(); KerbProxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;     KerbProxy.RequestSoapContext.Security.Tokens.Add(kerbToken);

      return KerbProxy.isRole(role);

    }

    Now look at the final project. The TestKerberosApp project acts as a driver program. Here are the steps.

    1. Navigate to TestKerberosApp project.
    2. Add a reference to the KerbAuth DLL (Right click on the project and select Add Reference)
    3. Create the following form with buttons and labels. Please refer to the source code for the complete listing.

      Figure 1.7 : Design form of the TestKerberosApp

    4. Add some code to initiate the button clicks. The code should be similar to:

    privatevoid btnName_Click(object sender, System.EventArgs e)

    {

      KerbAuth.KerberosHandler handler = new KerbAuth.KerberosHandler();  

      lblName.Text = handler.GetUser();

    }

     

    privatevoid btnRoles_Click(object sender, System.EventArgs e)

    {

       KerbAuth.KerberosHandler handler = new KerbAuth.KerberosHandler();

       if(handler.isRole(txtRole.Text))

         lblRole.Text = "The user DO have the role " + txtRole.Text;

       else

         lblRole.Text = "The user DOES NOT have the role " + txtRole.Text;

    }

    The code will invoke the KerbAuth DLL to communicate with the TestGateway Web service. The Kerberos authentication is hidden from the client application. Now set the TestKerberosApp as the default project and build the solution. When you run the application you should get an image similar to figure 1.8

    Figure 1.8: The Test application in action.

    Remember to turn on the tracing functionality with the "Diagnostics" settings of the WSE 2.0 (Figure 1.5). You should see the incoming and the out going SOAP packets from the Web service when you navigate to the correct files. You clearly see the Kerberos token embedded in the SOAP headers and the encrypted SOAP message is much heavier in size than the non encrypted one.

    << Introduction •       • The Future of Web Services >>

  • Other Articles
    Jul 7, 2005 - Hosting Indigo Web Services
    In the second article of his series on Indigo web services, Chris Peiris explains how to host an Indigo web service and examines the IIS, self hosting, and Windows Activation Service hosting options. He then provides step-by-step instructions and sample code for an IIS-hosted and self-hosted Indigo web service.
    [Read This Article]  [Top]
    Jun 8, 2005 - Indigo Programming Model
    In the first part of his series on Microsoft Indigo, Chris Peiris examines the basics of SOA, explains how Indigo fits into the picture and the problems it solves. He then introduces Indigo's programming model and finishes by building a sample Indigo web service using the Microsoft .Net Framework 2.0.
    [Read This Article]  [Top]
    Nov 10, 2004 - Business Intelligence with Microsoft SQL Server Reporting Services - Part 3
    Adnan Masood concludes his discussion of Microsoft SQL Server Analysis services and Microsoft SQL Server Reporting services. In the final part, he discusses Reporting Server web services and using custom code in reports.
    [Read This Article]  [Top]
    Jul 8, 2004 - Using IE's Web Service Behavior To Create Rich ASP.NET Applications
    This article explains the features of the IE Web service behavior and shows how to asynchronously communicate with an ASP.NET Web service directly from the client.
    [Read This Article]  [Top]
    Jul 6, 2004 - Using .NET and Excel 2003 To Validate E-Mails
    Calvin Luttrell shows how to validate e-mail addresses stored in Excel 2003 and provides a special function for solving that pesky problem Yahoo! mail servers cause.
    [Read This Article]  [Top]
    Jun 9, 2004 - Modifying Web Services Documentation
    This short article describes a quick and easy way to provide some security to an ASP.NET Web service by modifying its associated documentation file.
    [Read This Article]  [Top]
    Jun 2, 2004 - Kerberos Authentication with Web Services Enhancements 2.0
    Kerberos authentication is the cornerstone of Windows operating system authentication architecture. Web Services Enhancement 2.0 (WSE 2.0) extends Kerberos support to ASP.NET Web services. Chris Peiris explains the support for this new feature in WSE 2.0.
    [Read This Article]  [Top]
    Dec 15, 2003 - Realizing a Service-Oriented Architecture with .NET
    Chip Irek examines the architectural issues and component design issues of building a .NET application in a service-oriented architecture.
    [Read This Article]  [Top]
    Nov 24, 2003 - Consuming Asynchronous Web Services
    Thiru Thangarathinam shows how to use asynchronous Web services, Windows Service applications, server-based timer components and .NET XML API classes to create high-performance, scalable, and flexible applications.
    [Read This Article]  [Top]
    Nov 12, 2003 - Implementing Paging and XSLT Extensions Using XSLT in .NET - Part 2
    Part one showed how to transform XML data into HTML by using an XSL stylesheet from within a .NET application. This part explains how to make use of XSLT Extension objects and invoke a C# class method from an XSL stylesheet.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry

    internet.commediabistro.comJusttechjobs.comGraphics.com

    Search:

    WebMediaBrands Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs