There are various ways to authenticate a user to a Web Service. This article discusses one way to do it by the use of Cookies. As it could the case with a Web page sending a cookie to the browser, the same can be used from within a Web Service. This article assumes that you already have a Web Service project defined in the Visual Studio 2005 environment.
The goal here is to authenticate the user once so he can gain access to all the methods available in the Web Service. I have seen Web Services where the authentication scheme is sent at every method call. While this approach can be used to avoid establishing the structure of the authentication model at the client side, it does require the user to deal with this authentication scheme at every method call. I prefer to have it done once, by the use of a Login() method, such as we do for a Web site, so the authentication scheme is done automatically for all the other methods.
Login method
Let's define our first method in the Web Service. We will call it Login(). This method accepts two parameters. The first parameter is for the username and the second one for the password. This method returns a boolean, thus for the success of the operation, which is true or false. For now, we simply return true for our first step. Notice that I have named the class UniversalThread. This is what we will use as the class name for the purpose of this article.
Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols <WebService(Namespace:="http://www.universalthread.com/WebService/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class UniversalThread Inherits System.Web.Services.WebService ' Do the login for the specific user <WebMethod()> _ Public Function Login(ByVal tcUsername As String, ByVal tcPassword As String) _ As Boolean Dim llSuccess As Boolean Return llSuccess End Function End Class
Client side Web Service setup
From the client side, to test our Web Service, we simply add a button and put all the required code in it. For this purpose, we create a new Windows application. In the form, we simply drop a button control in it.
Next, we need to add a reference to this Web Service in our application. To do this, simply right click on the project and select Add Web Reference.
From the Add Web Reference dialog, we need to add the reference. For our test purposes, we are selecting the Web Service from our local PC, thus by the use of localhost.
When entering the proper URL, the Web Service definition should appear, thus, in our case, we simply have one method. To complete this operation, click on Add Reference. In Solution Explorer, you should now see a new item Web References with the reference under it. For the purpose of this article, we will name the reference to WebService. This is the reference we will use in the code to access our methods.
First test
To test the functionality of the Web Service, in the click event of the button, we will the code to define a Web Service object and do a simple call to the Login() method. Note that the Web Service simply returns the value of llSuccess for now, which has a default value of false. Thus, by executing this form, and by clicking on the button, we should obtain a messagebox with the text false in it.
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles Button1.Click Dim loWebService As WebService.UniversalThread = New WebService.UniversalThread Dim llSuccess As Boolean llSuccess = loWebService.Login("Username", "Password") MessageBox.Show(llSuccess) End Sub End Class
Establishing the authentication
Back to our Web Service definition, the fun part is when we authenticate the user as to know if he is authorized to access the Web Service and do whatever is necessary to keep this authentication valid across the calls of all the other methods. We will adjust our Login() method to verify that the username and password are valid. We will simply verify that the username received as the first parameter is equal to "Username" and that the password received, the second parameter, is equal to "Password". If that is valid, we will create a cookie named Session with the value "01234567".
Public Function Login(ByVal tcUsername As String, ByVal tcPassword As String) As Boolean Dim llSuccess As Boolean ' See if this user has provided the proper username and password If tcUsername = "Username" And tcPassword = "Password" Then llSuccess = True End If ' If llSuccess is True then we can create the cookie If llSuccess Then System.Web.HttpContext.Current.Response.Cookies("Session").Value = "012345678" End If Return llSuccess End Function
' Return the time of the server <WebMethod()> _ Public Function GetTime() As String CheckLogin() Return System.DateTime.Now() End Function ' Check for the login Public Function CheckLogin() As Boolean Dim llSuccess As Boolean Dim loCookie As System.Web.HttpCookie Dim lcSession As String Dim lcError As String loCookie = System.Web.HttpContext.Current.Request.Cookies("Session") lcError = "" If Not loCookie Is Nothing Then lcSession = loCookie.Value.ToString() llSuccess = True Else lcError = "You have to login in order to use the Web Service." llSuccess = False End If If llSuccess = False Then Throw New System.Exception(lcError) End If End Function
Final setup on the client side
As everything has been done on the server side, we can now adjust our client side code to benefit of this authentication and proceed with the call of another method. We will adjust the code of the click event of the button to be a little bit more detailed. It will make sure the authentication is properly established. If not, it will display a messagebox with the related text and stop the execution of the code. When the authentication is properly established, the execution of the code will continue and call the GetTime() method.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles Button1.Click Dim loWebService As WebService.UniversalThread = New WebService.UniversalThread Dim llSuccess As Boolean Dim lcTime As String llSuccess = loWebService.Login("Username", "Password") If llSuccess = False Then MessageBox.Show("The authentication is not valid.") Exit Sub End If lcTime = loWebService.GetTime() MessageBox.Show(lcTime) End Sub
This is normal as in order for the client side to establish the proper setup, when the authentication succeeds, we need to add one more thing. By default, the Visual Studio environment will not setup the cookie. We have to turn this option ON. This can be done by doing one simple adjustment in our code.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles Button1.Click Dim loWebService As WebService.UniversalThread = New WebService.UniversalThread Dim llSuccess As Boolean Dim lcTime As String loWebService.CookieContainer = New System.Net.CookieContainer llSuccess = loWebService.Login("Username", "Password") If llSuccess = False Then MessageBox.Show("The authentication is not valid.") Exit Sub End If lcTime = loWebService.GetTime() MessageBox.Show(lcTime) End Sub
This article was providing a simple authentication model which can be used. In a more advanced article, the proper username and password should be passed, the Web Service code should apply those username and password values against a database validation and so on. But, it should provide you a good overview of a simple authentication model to start with.
Source code