top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Using Forms Authentication With Web Services

+1 vote
326 views

Introduction

ASP.NET Forms authentication is one of the most flexible way to authenticating users. Typically under such scheme you will have user ids and passwords in some database. You will then present a form to the user that accepts the credentials. Then at server side you check whether the credentials are valid or not. Based on this validation you will display some error or success message. Forms authentication works very well with web forms. Can you use it with web services? With some tricks - Yes. In fact in this article I am going to show how to do just that. Keep reading...

Problems while using Forms Authentication with Web Services

Before understanding the problem in implementing forms authentication with web services, let us first see how forms authentication works in a typical scenarios.

  • User is presented with a web form where he can enter user id and password
  • He enters user id and password and submits the form
  • At server side, you validate the values he entered against values stored in database
  • If the authentication fails you take him to the login page again and display some error message
  • If authentication succeeds you take him to the main page of your application
  • If user tries to access a page without logging in, Forms Authentication is clever enough to redirect him to the login page automatically

As you can see, Forms Authentication greatly depends on a physical login page to accept the user credentials. You can easily provide such page in a web application. But what if you want to use it with web service application? You certainly do not have any user interface for web services. Also, you must be knowing that forms authentication works based on an authentication cookie that is passed to and from with each request made to the application. Your web service is not a part of your web application and maintaining this authentication cookie across requests in a session is problem.

Developing the web service

Now, that we are clear with the problems let us see how to solve them. The first we need to do is to make appropriate changes to web.config to enable forms authentication. The following markup shows this in detail:

  <system.web>
	<authentication mode="Forms">
		<forms name="CookieName" 
		loginUrl="service1.asmx" 
		protection="All" 
		timeout="60" path="/" />
	</authentication> 
    <authorization>
        <deny users="?" />
    </authorization>
  </system.web>

Here, we set authentication mode to "Forms" and deny access to anonymous users. Next, we will write three web methods for the web service - Login, GetLoginStatus and Logout. The names are self explanatory and need no explanation. Following code from web service code-behind file shows how the web service looks:

Public Class Service1
    Inherits System.Web.Services.WebService
    
     _
    Public Function Login(ByVal UserName As String, 
    ByVal Password As String) As Boolean
        If UserName.Length > 0 And Password.Length > 0 Then
            FormsAuthentication.SetAuthCookie(UserName, False)
            Return True
        Else
            Return False
        End If
    End Function

     _
    Public Function GetLoginStatus() As String
        If Context.User.Identity.IsAuthenticated = True Then
            Return "Logged In"
        Else
            Return "Not Logged In"
        End If
    End Function

     _
    Public Function Logout()
        If Context.User.Identity.IsAuthenticated = True Then
            FormsAuthentication.SignOut()
        End If
    End Function

Note that in each web method we set EnableSession to True. This allows us to access to the session object. In the Login method we simply call FormsAuthentication.SetAuthCookie() method passing supplied user name. Consumer of this web service must call Login() before calling any other method else he will not be allowed to consume the functionality. The GetLoginStatus() method simply returns whether user is logged into the system or not. If your web service has any other web methods then all such web methods should check Context.User.Identity.IsAuthenticated property before processing the request. The Logout() method calls FormsAuthentication.SignOut() and then onwards user will not be able to consume.

Developing the Web Service Consumer

If you are consuming the web service we developed above from a windows forms application, there are no much issues as there is no concern of 'state less' programming. However, if you want to consume this web service via ASP.NET web forms then you need to do additional things. We will now develop a client web form that shows how to do that.

We will create a web form that has three buttons - Login, Check Login Status and Logout. The Click event handler of Login button contains following code:

Dim x As New localhost.Service1()
Dim cc As New CookieContainer()
Dim sessioncookie As Cookie
Dim cookiecoll As New CookieCollection()

x.CookieContainer = cc
x.Login("user1", "password1")
cookiecoll = x.CookieContainer.GetCookies
(New Uri("http://localhost"))
Session("sessioncookie") = cookiecoll("CookieName")

Note that you need to import System.Net namespace as classes such as CookieContainer reside within it. Let us see how the code works.

  • We first create an instance of web service proxy class (x)
  • The proxy class has a property called CookieContainer. This property represents the collection of cookies that are to be passed to the web service along with the request.
  • Then we call Login() method
  • Remember that Login() method sets an authentication cookie in the response. This cookie is trapped and stored in a session variable. Note that "CookieName" is the name we used in forms tag.

Once we are logged in, we can call any other web methods. Following is the code inside the Click event of 'Check Login Status' button.

Dim x As New localhost.Service1()
Dim cc As New System.Net.CookieContainer()
Dim sessioncookie As New System.Net.Cookie()
x.CookieContainer = cc
sessioncookie = CType(Session("sessioncookie"), 
System.Net.Cookie)
If Not sessioncookie Is Nothing Then
	x.CookieContainer.Add(sessioncookie)
End If
Label1.Text = x.GetLoginStatus()

Since the web service decides whether a method call is authenticated or not based on the forms authentication cookie, we add the previously stored cookie with each method call. Then we call the actual web method. This is necessary because we are working in state less environment. The web service proxy class is created and destroyed each time the web form is processed. So, with each request you need to populate its CookieContainer again and again.

The LogOut() method works as follows:

Dim x As New localhost.Service1()
Dim cc As New System.Net.CookieContainer()
Dim sessioncookie As New System.Net.Cookie()
x.CookieContainer = cc
sessioncookie = CType(Session("sessioncookie"), 
System.Net.Cookie)
If Not sessioncookie Is Nothing Then
	x.CookieContainer.Add(sessioncookie)
End If
x.Logout()
Session.Remove("sessioncookie")

Here, the code is almost identical to the previous code snippet. However, we call LogOut() method in the end. Once we call LogOut() we also remove the reference variable from the session that points to the authentication cookie.

That's it! You have just developed forms authentication mechanism for web services. I hope you must have enjoyed reading the article. See you soon with some more interesting stuff.

posted Nov 26, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Introduction

In the previous article in this series we saw how to use SOAP headers to authenticate a web service. In this article I will show you how you can use windows credentials to authenticate the consumer of your web service. Windows authentication is commonly used in intranet scenarios such as corporate portals.

How it works?

You can enable windows authentication for your web applications using web.config file. You need to set authentication mode to Windows in the <authentication> section. Additionally you need to set <authorization> section to deny anonymous access. Once you set these parameters in the web.config file the windows credentials of client machine (i.e. the machine which is accessing the web service) will be automatically passed to the web service. In side the web service you can then use Context.User.Identity.Name to get the user name of the user. In case client is not logged in to the domain, IE will pop up a dialog box to enter user id and password. Once user enters valid credentials he will be allowed to consume the web service.

Source Code

The sample source code provided contains two VS.NET projects. One is web service project that authenticates the user. The other is web application that consumes the web service.

READ MORE

Introduction

Typically applications are written either as forms based desktop applications or as web based applications. In some cases you can also use ActiveX controls hosted in IE. .NET Windows Forms provide an attractive alternative to download and run forms based applications locally. In this article I will explain you what a smart client application is and how it offers an attractive model if coupled with ASP.NET web services.

What are Smart Client Applications?

Smart Client Applications are nothing but Windows Forms applications accessed over Internet using browser. You develop Smart Client applications as normal Windows Forms Applications and then place the executable in an IIS virtual root. Then users can access the EXE by typing its URL in their browser. This is how a Smart Client Application works:

  • User navigates to the application EXE by typing URL in the browser
  • The EXE gets downloaded on the client machine
  • The downloaded EXE gets installed in Global Assembly Cache
  • The EXE is loaded from GAC and displayed to the user

Advantages of Smart Client Applications

Following are the advantages of Smart Client Applications:

  • Rich user interface
  • Application gets downloaded for the first time and gets installed in GAC. Future requests are served from this downloaded version.
  • In case original application changes the new version is automatically downloaded
  • Dependencies get downloaded as and when required and not all at once

Disadvantages of Smart Client Application

Following are the disadvantages of Smart Client Applications:

  • The MSIL EXE gets downloaded at client side. So, takes more time to load the first time
  • Configuration files (app.config) can not be used easily as in case of pure desktop application
  • Since MSIL EXE gets downloaded at client there is risk of client "de-compiling" your code
  • There is no central control on the application once it gets deployed to the users.

Smart Clients and Web Services

From above advantages and disadvantages there are two things that need to be take care:

  • Somehow your business logic should be prevented to be downloaded at client end. This will reduce the risk of client "decompiling" your efforts.
  • Configuration needs to be taken care by some other means

Above problems can be solved if you use ASP.NET web services along with the Smart Client front end. In such an architecture, the smart client simply acts as a front end to your business logic. The core business logic resides in web services. The smart client consumes the web services. This eliminates the risk of somebody reverse engineering your work. Since web services do the majority of work such as data access; web.config can be easily used for configuration purposes (connection string, file paths etc.). We can also centrally control the business logic since no business rules will ship with the smart client.

Sample Application

The sample application provided with this article contains two VS.NET projects - a web service and a windows forms project. In order to run the projects follow these steps:

  • Unzip the supplied ZIP file in a folder
  • Create two virtual directories under IIS
  • The one virtual directory should point to the web service project
  • The another virtual root should point to the windows forms application
  • Now navigate to the EXE from Internet Explorer
  • The smart client EXE will be downloaded on the client and executed
READ MORE

Introduction

While working with web services one of the commonly faced question is - How do I secure my web service? One aspect of security is preventing anonymous access to the web service. This can be done in various ways such as passing user id and password with each web method call. One elegant alternative is to use SOAP headers to pass this authentication information. This code sample shows how to use SOAP headers to pass authentication information to the web service.

About SOAP Headers

Every SOAP message consists of SOAP body and optional header. SOAP header serve similar purpose as familiar HTTP headers such as passing some information. Note that SOAP headers are passed as plain text over the network. This means that if you need strong security measures you may not like to use them without some kind of encryption.

About Sample Source Code

A ZIP file is provided with this article for download. The ZIP contains two VS.NET projects - web service and web service client. The client passes user information such as User ID and Password in the SOAP headers to the web service. The web service then authenticates the user and sends back response accordingly.

READ MORE
...