Click here to Skip to main content
Click here to Skip to main content

Web Services Security using Username and Kerberos Tokens

By , 19 Sep 2005
 

Introduction

The following article deals with the implementation of security in Web Services. It briefs about how to make Web Services allow only those requests which have been validated for user name or binary tokens. The following article shows how to create such a service and how to invoke such a service. The platform used for development is Windows XP. Username tokens can be validated against built-in accounts. But for the implementation of Kerberos tokens, the machine needs to belong to a domain and should have the logged-in user listed in the Active Directory. The Kerberos key Distribution Center (KDC) issues tickets on validation.

Using the code

  1. Make sure you have Microsoft Web Services Enhancements (WSE) 2.0 installed.
  2. Create a blank solution.
  3. Add two C# projects to the blank solution.
    • ASP.NET Web Service (C#). Name it "service".
    • Windows Application (C#). Name it "client".
  4. Enable WSE on both the projects. This can be done by right clicking on the projects and clicking on WSE 2.0 Settings.
    • Make sure that the ASP.NET service has both the WSE enhancements and the SOAP Extensions enabled.
    • The client only needs to have WSE enabled.
  5. There are two parts in the project:
    • UserName Token
    • Kerberos Token
  6. Creating the service that will accept a UserName or a Kerberos Token and after validating will execute the WebMethod.

The code

  1. Namespaces used:
    using Microsoft.Web.Services2;
    using Microsoft.Web.Services2.Security;
    using Microsoft.Web.Services2.Security.Tokens;
  2. A method ValidateToken() is called before actually executing the web method.
    [WebMethod]
    public long perform(long a,long b)
    {
        //check whether the request is from a valid source or not.
        if (ValidateToken())
            return a+b;
        else
            return long.MinValue;
    }
  3. Extracting and verifying the token from the SOAP context:

    Copy all the elements from the SOAP context into a collection.

    //The Security elements are extracted from
    // the SOAP context and stored in a collection
    SecurityElementCollection e = 
       RequestSoapContext.Current.Security.Elements;

    Now iterate through the elements to find the message signature.

    //The collection containing the SOAP Context 
    //is iterated through to get the message signature
    foreach( ISecurityElement secElement in e ) 
    {

    Now find the MessageSignature if present in the SOAP context.

    //The collection containing the SOAP Context 
    //is iterated through to get the message signature
    foreach( ISecurityElement secElement in e ) 
    { 
        if( secElement is MessageSignature ) 
        {

    Now check whether it is a Username token or a Kerberos token and do the needful if validated.

            SecurityToken sigTok = msgSig.SigningToken; 
            //check whether the signature contains a username or a kerberos token
            if( sigTok is UsernameToken ) 
            {
                //This checks against the BuiltIn Users
                return sigTok.Principal.IsInRole( @"BUILTIN\Users" );
            }
            else if( sigTok is KerberosToken )
            {
                //The logged in user is checked against 
                //the Kerberos Key Distribution Center(KDC).
                return sigTok.Principal.Identity.IsAuthenticated;
            }
  4. Creating the client.
    1. Namespaces used are:
      using Microsoft.Web.Services2.Security;
      using Microsoft.Web.Services2.Security.Tokens;
    2. Add a web proxy for the service that we just created.

    3. UserName Token -- the following code creates a UserName Token:
      //declare any Security Token
      SecurityToken token=null;
      switch (option)
      {
          case "UserName":
          {
              try
              {
                  //create a username Token.
                  UsernameToken unToken=new UsernameToken(textBox1.Text, 
                            textBox2.Text,PasswordOption.SendPlainText);
                  //assign the any SecurityToken an Username Token.
                  token=unToken;
              }
              catch(Exception ex)
              {
                  MessageBox.Show(ex.Message);
                  return;
              }
              break;
          }
    4. Kerberos Token -- The following code creates a Kerberos Token:
          case "Kerberos":
          {
              try
              {
                  //create a kerberos Token.
                  KerberosToken kToken = 
                    new KerberosToken(System.Net.Dns.GetHostName() );
                  //assign the any SecurityToken an Username Token.
                  token=kToken;
              }
              catch(Exception ex)
              {
                  MessageBox.Show(ex.Message);
                  return;
              }
              break;
          }
  5. Now check whether the security token could be obtained or not. If yes then we create a class from the proxy that has been generated and we add the token acquired to the RequestSoapContext of the call.
    if (token == null)
        throw new ApplicationException( "Unable to obtain security token." );
    
    // Create an instance of the web service proxy that has been generated.
    SecureServiceProxy.Service1Wse proxy = 
       new client.SecureServiceProxy.Service1Wse();
    
    //set the time to live to any value.
    proxy.RequestSoapContext.Security.Timestamp.TtlInSeconds = 60;
    
    
    // Add the SecurityToken to the SOAP Request Context.
    proxy.RequestSoapContext.Security.Tokens.Add( token );
    
    // Sign the SOAP message with a signatureobject.
    proxy.RequestSoapContext.Security.Elements.Add(new 
                          MessageSignature( token ) );
  6. Finally call the service.
    // Create and Send the request
    long a=long.Parse(textLong1.Text);
    long b=long.Parse(textLong2.Text);
    //call the web service.
    long result=proxy.perform(a,b);
    //Display the result.
    MessageBox.Show(a + " + " + b + " = " + result.ToString());

Points of Interest

I had forgotten to add the Web Service Enhancements to the WSE 2.0 service and that ate a lot of my time.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Abhishek Chatterjee
Web Developer
India India
Member
Abhishek is working as part of the Web Services COE (Center of Excellence) for Infosys Technologies Ltd., a global IT consulting firm, and has substantial experience in publishing papers, presenting papers at conferences, and defining standards for SOA and Web services.
 
Abhishek Chatterjee 's Home Page

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionWCF ServicememberMember 255600326 Apr '11 - 20:51 
Hi ,
 
How to acheive the same stuff through WCF service with .net framework 4?
QuestionWhere is ....Wse class ?????memberFKazi18 Feb '10 - 0:24 
Thanks Abhi,
 
But will you please let me know how to get "Service1Wse". I am getting an error for this class
Please let me know as soon as possible
GeneralUsing Windows Login/Kerboros Authentication between client and servermemberAditya P Gupta25 Nov '07 - 23:01 
Hi Abhishek,
 
I read your article and found it interesting. However I have a query, I basically want to initiate a single sign-in sort of mechanism between my client application and server. Basically something like we use for SQL Server authentication (Windows logged-in user account). I want to provide my client application the option of saying use windows authentication, now when this login request/connection request hits the server. Server should be able to validate this Token and then allow client access to resources based on the token.
 
I would appreciate if you can help me on this.
 
Regards,
Aditya
QuestionEXception while executing USerName TokenmemberAbhishek Chatterjee30 May '07 - 14:29 
i have created a web service and client for the same and using username token "UserNamePolicy".when i exceute the code it throws and Web Service Error ->Specified arguemnt was out of range of valid Values
Parameter name:policy "UserNamePolicy"is not configured in the System. Kindly help

 

 
"If u believe in psychokinesis then raise my hand." Smile | :)

AnswerRe: EXception while executing USerName TokenmemberAbhishek Chatterjee30 May '07 - 14:31 
Hi Kitu,
 
could not answer ur mail as ur settings did not allow me to send mails.. so answering here..
 
i guess u r using wse 3.0 for implementing security.
u have to go thru the entire wizard to create the policy file properly. also open the policy file created and check whether non allowed values have been added into the xml file.

 
"If u believe in psychokinesis then raise my hand." Smile | :)

Generalserver without IISmemberfrohwein27 Mar '07 - 10:48 
Hi,
 
I use a standalone soap service (without IIS) running as a Win32 service on a number of xp
systems.
How can I use soap security (signing and/or encryption) in this case, so without IIS?
 
greetings
Rob

GeneralRe: server without IISmemberAbhishek Chatterjee27 Mar '07 - 17:38 
if u r running standalone soap services then u can add the security headers directly to the soap message.. u do not need to know what protocol is being used to communicate
 
"If u believe in psychokinesis then raise my hand." Smile | :)

QuestionWSE 3.0memberBernhard Hofmann26 Mar '07 - 22:54 
Could you suggest/write an article on how to do this with WSE 3.0?
 
Don't worry, nobody lives forever.

AnswerRe: WSE 3.0memberAbhishek Chatterjee26 Mar '07 - 23:01 
try wse 3.0 turnkey security scenarios.
they have detailed implementations about plausible scenarios...
 
"If u believe in psychokinesis then raise my hand." Smile | :)

GeneralRe: WSE 3.0memberBernhard Hofmann27 Mar '07 - 1:20 
Could you suggest a suitable link? There seems to be so much noise on WSE 3.0 that I can't find the information on exactly how to "activate" a turnkey policy.
 
Don't worry, nobody lives forever.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 19 Sep 2005
Article Copyright 2005 by Abhishek Chatterjee
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid