5,696,576 members and growing! (16,342 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Intermediate

Web Service Authentication

By faina

A simple mechanism to authenticate users to a WebService.
C#, Windows, .NET 1.1, .NET, WebForms, ASP, ASP.NET, Visual Studio, VS.NET2003, Dev

Posted: 19 Jan 2005
Updated: 19 Apr 2007
Views: 117,973
Bookmarked: 108 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
16 votes for this Article.
Popularity: 4.82 Rating: 4.00 out of 5
1 vote, 6.3%
1
0 votes, 0.0%
2
2 votes, 12.5%
3
9 votes, 56.3%
4
4 votes, 25.0%
5

Sample Image - WebServiceAuthentication.gif

Introduction

This is a simple mechanism to authenticate users to a Web Service, using a Time Token and MD5 Hashing to encrypt password.

Background

In CodeProject, you can find at least two others' mechanism to authenticate users to a Web Service. Dan_P wrote Authentication for Web Services as a Simple authentication for web services using SOAP headers. But the username and password are send in clear text and there is no encryption for the data. HENDRIK R. is the author of An introduction to Web Service Security using WSE, that is really a complete solution, but too much complicated for my purposes. The username is send in clear text, but it is possible to use Password Digest to encrypt the password. The data are encrypted using XML Encryption specification to encrypt portions of the SOAP messages.

My solution is something in the middle of the above two. The username is send in clear text, but I use MD5 to encrypt the password. I do not need to send sensitive data, so the data returned by the Web Service is not encrypted.

Using the code

The basic idea is to send UserName and Password from the client to the Web Service using MD5 Hash Code as encryption system. In this way, the password never travels in clear over the network. The Web Service retrieves the user password from a DB or anything else and uses the same MD5 algorithm to test if the password is correct. To be sure that if someone intercepts the Hash, this can be used to authenticate in a later time, I added a timestamp before hashing the Key string. Last, as we are not always on the same server and/or the client clock may be in a different Time Zone or simply not synchronized, I added the possibility to request a Token containing the time mark to the server.

I provided a sample in ASP.NET C# for the client side, but it is possible to use any language: ASP classical JScript or VBScript, PHP, Python, etc. Anyway, on the client side we need to build up the Key using UserName, Password and the hashed timestamp Token previously got from the same Web Service. We can then call the Service and we will get the answer (or an authentication failure warning) that is displayed on the web page.

private void ButtonUseToken_Click(object sender, System.EventArgs e)
{
    string ret;
    string UserName, Password, ServiceName, Token;
    string Key, ToHash;

    UserName=this.TextBoxUserName.Text;
    Password=this.TextBoxPwd.Text;
    ServiceName=this.TextBoxService.Text;
    Token=this.TextBoxToken.Text;
    ToHash=UserName.ToUpper()+"|"+Password+"|"+Token;
    Key=Hash(ToHash)+"|"+UserName;

    ServicePointReference.ServicePoint Authenticate = 
                             new ServicePointReference.ServicePoint();
    ret=Authenticate.UseService(Key, ServiceName);
    this.ServResponse.Text=ret;
}

The MD5 Hash procedure is very simple in C#; this one was written by Vasudevan Deepak Kumar in Securing Web Accounts.

private string Hash(string ToHash)
{
    // First we need to convert the string into bytes,

    // which means using a text encoder.

    Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

    // Create a buffer large enough to hold the string

    byte[] data = new byte[ToHash.Length];
    enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

    // This is one implementation of the abstract class MD5.

    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] result = md5.ComputeHash(data);

    return BitConverter.ToString(result).Replace("-", "").ToLower();
}

On Web Service server side I implemented just three Web Methods:

GetToken is used to get the Time-marked token. The token you get this way, is intended to be used in the basic Authenticate method, or in the UseService that can also verify the access rights for the users authenticated to the requested service. The core of the system is implemented by TestHash. Here the password is hard-coded, but in the sample provided you have also the code to get it from a database:

private bool TestHash (string HashStr, 
             string UserName, int minutes, string ServiceName)
{
    string Pwd, ToHash;
    string sResult, sResultT, sResultToken;
    try
    {
        // JUST FOR TEST: the password is hard-coded:

        Pwd="SeCrEt";

        DateTime dt = DateTime.Now;
        System.TimeSpan minute = new System.TimeSpan(0,0,minutes,0,0);
        dt = dt-minute;
        //before hashing we have:

        //USERNAME|PassWord|YYYYMMDD|HHMM

        ToHash=UserName.ToUpper()+"|"+Pwd+"|"+dt.ToString("yyyyMMdd")+
                                             "|"+dt.ToString("HHmm");
        sResult = Hash(ToHash);
        //TokenWeGotBefore

        ToHash=dt.ToString("yyyyMMdd")+"|"+dt.ToString("HHmm");
        sResultToken = Hash(ToHash);
        //USERNAME|PassWord|TokenWeGotBefore

        ToHash=UserName.ToUpper()+"|"+Pwd+"|"+sResultToken;
        sResultT = Hash(ToHash);
    
        if ((sResult==HashStr) || (sResultT==HashStr)) 
            return true;
        else
            if (minutes==0) // allowed max 2 minutes - 1

                            // second to call web service

            return TestHash (HashStr, UserName, 1, ServiceName);
        else
            return false;
    }
    catch
    {
        return false;
    }
}

To request a hashed time-stamped Token to the Web Service the method is:

[WebMethod]
public string GetToken ()
{
    string ToHash, sResult;
    DateTime dt = DateTime.Now;
    ToHash=dt.ToString("yyyyMMdd")+"|"+dt.ToString("HHmm");
    sResult = Hash(ToHash);
    return sResult;
}

The method that checks the user authentication is also kept very simple; in a real application you normally need to access a database to check the authentication level and may need to return some data to the caller:

[WebMethod]
public string UseService (string Key, string ServiceName)
{
    string [] HashArray;
    string UserName, level;

    // Key string: HASH|User|OptionalData

    HashArray=Key.Split('|');
    level = "-1";    //defaul level


    if (TestHash(HashArray[0], HashArray[1], 0, ServiceName))
    {
        try
        {
            UserName=HashArray[1];
            // JUST FOR TEST: the User authentication level is hard-coded

            // but may/shuold be retrieved from a DataBase

            switch (UserName)
            {
                case "MyUserName":
                    level="1";
                    break;
                case "OtherUser":
                    level="2";
                    break;
                default:
                    level="-1";
                    break;
            }
            if (level=="1") return "YOU ARE AUTHORIZED";
        }
        catch (Exception exc)
        {
            return "Authentication failure: " + exc.ToString();
        }
    }
    return "Authentication failure";
}

Points of Interest

TestHash checks to see if the Hash contains a timestamp or an already-hashed token, and calls itself once again in case of failure: if someone is calling the service, let's say, at 11:34:58 the Key is valid from 11:34:00 until 11:35:00, that is during two minutes.

The client side may be implemented in any language: ASP classical, JScript or VBScript, PHP, Python, etc. I have intention to post this code too next time...

History

  • 01/20/2005 - Article created.

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

faina



Occupation: Web Developer
Location: Italy Italy

Other popular C / C++ Language articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
GeneralJust wanted to say thanks,memberpimpmurph8:49 7 Aug '07  
Generalneed help on the source code files [modified]memberCheng Dehua18:02 12 Apr '07  
GeneralRe: need help on the source code filesmemberfaina22:16 18 Apr '07  
GeneralRe: need help on the source code filesmemberCheng Dehua22:44 18 Apr '07  
GeneralFalse sense of securitymemberDEGT22:25 5 Apr '07  
GeneralRe: False sense of securitymemberfaina23:52 5 Apr '07  
GeneralRe: False sense of securitymemberDewey23:00 19 Apr '07  
QuestionRe: False sense of securitymemberdiegotegravi10:14 30 Aug '07  
GeneralWhat should be the setting in IIS [modified]membernzhuda16:47 13 Dec '06  
GeneralHelp me!!memberomkarphatak8:01 2 Dec '06  
GeneralRe: Help me!!memberfaina21:07 3 Dec '06  
GeneralRe: Help me!!memberomkarphatak18:46 4 Dec '06  
GeneralRe: Help me!!memberashit197811:36 25 Sep '07  
Generalneed help on running this projectmemberm-xi5:55 1 Mar '06  
GeneralRe: need help on running this projectmemberfaina21:37 1 Mar '06  
GeneralRe: need help on running this projectmemberm-xi3:30 6 Mar '06  
GeneralRe: need help on running this projectmemberCheng Dehua20:57 14 Apr '07  
GeneralRe: need help on running this projectmemberCheng Dehua21:46 18 Apr '07  
GeneralUnencrypted Text ?memberEniac04:44 14 Nov '05  
AnswerRe: Unencrypted Text ?memberfaina23:21 14 Nov '05  
GeneralnamespacesmemberHirahi.0:50 9 Aug '05  
GeneralAuthentication failurememberbaltika6:06 28 Apr '05  
GeneralI get error running this projectmemberFMGToronto10:59 19 Apr '05  
GeneralRe: I get error running this projectmemberFMGToronto11:26 19 Apr '05  
Generalbetter implementationmemberashish desai6:28 31 Jan '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Apr 2007
Editor: Sean Ewington
Copyright 2005 by faina
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project