Click here to Skip to main content
13,290,261 members (52,375 online)
Click here to Skip to main content
Add your own
alternative version


56 bookmarked
Posted 10 Feb 2009

Retrieve a List of Authenticated Users using ASP.NET, AJAX, and FormsAuthentication

, 26 Feb 2009
Rate this:
Please Sign up or sign in to vote.
This article explains how to retrieve and display a list of all the authenticated users on an ASP.NET WebSite


As a Web developer working in a small company, I often encountered the same issue: every time I wanted to release a new version of a Web application, I had to call / send an e-mail to every lovely user in order to ask them to leave the application. The fact is that most of them weren't using it at the moment I was planning to launch the update. At the end, everyone was angry because of the time they lost answering my phone calls, especially those who were in the middle of an exciting Freecell game, or watching their friends' pictures on Facebook.

I decided to put an end to it by developing a small Web page that would tell me who is online. The principle is really simple: on the first load of every page in my WebSite, I check if the current user is authenticated. If this is the case, I check if he's already part of the authenticated users' list (a generic List of string objects). If he's not in the list, I add him into it. When the user navigates to another page, or closes his browser, I remove him from the authenticated users' list. This is done using a little bit of JavaScript with a call to a WebService.


If you're not familiar with FormsAuthentication, you may want to take a look at this article:

This blog explains how to use the ASP.NET Cache and Session State storage:

Finally, this page from MSDN describes and shows a sample of the JavaScript "onbeforeunload" event:

Using the Code

Your Web.config file should include the following sections:


    <!-- Use FormsAuthentication in the WebSite -->
    <authentication mode="Forms">
      <forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" />

    <!-- References to the Ajax assemblies -->
        <compilation debug="true">
        <add assembly="System.Web.Extensions, Version=1.0.61025.0, 
		Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Design, Version=, Culture=neutral, 
		PublicKeyToken=B03F5F7F11D50A3A" />
        <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, 
		Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

    <!-- This is needed to make the WebService work properly -->
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" 

	System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
	PublicKeyToken=31bf3856ad364e35" />
      <add verb="*" path="*_AppService.axd" validate="false" 

	System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
	PublicKeyToken=31bf3856ad364e35" />
      <add verb="GET,HEAD" path="ScriptResource.axd" 

	System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
	PublicKeyToken=31bf3856ad364e35" validate="false" />

    <!-- This is needed to make Ajax work properly -->
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, 
	System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
	PublicKeyToken=31bf3856ad364e35" />

    <!-- This is optional, but if you don't register the 
	System.Web.Extensions library in the Web.config, 
	you'll have to do it in the MasterPage-->
        <add tagPrefix="asp" namespace="System.Web.UI" 

		assembly="System.Web.Extensions, Version=1.0.61025.0, 
		Culture=neutral, PublicKeyToken=31bf3856ad364e35" />



This is the code-behind for the login page. Nothing fancy here, just a few lines of code that check if the specified username and password are valid. This is the place to put your authentication logic, but keep in mind that the username is the one that will be displayed in the "authenticated users" page. So you probably don't want to use an id here. If you really can't use the username of the login page (for example, if this username is not relevant), you should store the "real" UserName in a Session variable during your authentication process, then use something like Session["UserName"].ToString() to retrieve it.

/// <summary>
/// Triggers when the page loads
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)

/// <summary>
/// Triggers when the user logs in
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void AuthenticatedUsersLogin_Authenticate(object sender,
AuthenticateEventArgs e)
  //Replace the following code by your own authentication logic
  string userName = AuthenticatedUsersLogin.UserName;
  string password = AuthenticatedUsersLogin.Password;
  if (userName.Length > 0 && password.Length > 0)
	FormsAuthentication.RedirectFromLoginPage(userName, true);


All your WebPages must inherit from this class (except for the login page). It stores the authenticated users name in a string List.

/// <summary>
/// Stores the authenticated users in a string List
/// </summary>
public class BasePage : Page
    /// <summary>
    /// Triggers every time a page loads
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    //If the page loads for the first time and if the current user is authenticated,
    //we add him to the authenticated users' list
        if (!IsPostBack &&  HttpContext.Current.Request.IsAuthenticated)

    /// <summary>
    /// Adds the current user's name to the authenticated users' list
    /// </summary>
    protected void RegisterUser()
    //We retrieve the list of the authenticated users
        List<string> authenticatedUsers = AuthenticatedUsersList;

     if (!authenticatedUsers.Contains(UserName))
        //If the current user is not already in the authenticated users' list,
        //we add him to the list
        //Then we save the authenticated users' list
        AuthenticatedUsersList = authenticatedUsers;

    /// <summary>
    /// Gets or sets a list of all the authenticated users
    /// </summary>
    protected List<string> AuthenticatedUsersList
            //If the Cache is empty, we add an empty List in it
            if (Cache["AuthenticatedUsers"] == null)
                Cache["AuthenticatedUsers"] = new List<string>();
            return (List<string>)Cache["AuthenticatedUsers"];
        set { Cache["AuthenticatedUsers"] = value; }

    /// <summary>
    /// Gets the current user's name
    /// </summary>
    protected string UserName
        //If you don't want to use the Identity.Name object, you should store the
        // UserName in a Session variable in the Login page.
        //Then use something like Session["UserName"].ToString() to retrieve it.
            return HttpContext.Current.Request.IsAuthenticated
                ? HttpContext.Current.User.Identity.Name
                : string.Empty;


This is the page that displays the list of the authenticated users. You just need a label and you're done. Of course you should add some links to the other pages, otherwise you won't be able to go back to your WebSite !

/// <summary>
/// Triggers when the page loads
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
    //If this is the first time that the page loads, when call the method that
    //will display the authenticated users
    if (!IsPostBack) DisplayAuthenticatedUsers();

/// <summary>
/// Displays the authenticated users
/// </summary>
private void DisplayAuthenticatedUsers()
    List<string> authenticatedUsersList = AuthenticatedUsersList;
    if (authenticatedUsersList.Count > 0)
        foreach (string user in authenticatedUsersList)
            lblAuthenticatedUsers.Text += string.Format("<li>{0}</li><br />", user);
    else lblAuthenticatedUsers.Text = "No one is authenticated";


Placing the following code in a MasterPage saves us from the pain of adding it in each of the WebSite's pages. Basically I first added a reference to my WebService between the <asp:ScriptReference> tags. Then I added my JavaScript code that will be triggered during the window.onbeforeunload event. This will call the WebService's UnregisterUser() method, used to remove the current user from the authenticated users' list.

<form id="form1" runat="server">
        <asp:ScriptManager ID="AuthenticatedUsersScriptManager" runat="server">
                <asp:ServiceReference Path="~/AuthenticatedUsersWebService.asmx" />

        <script type="text/javascript" language="javascript">
            //Occurs when the user leaves the current page, or closes the browser
            window.onbeforeunload = RemoveUser;

            function RemoveUser()
                //We call the UnregisterUser() method located in the WebService
                result = AuthenticatedUsersWebService.UnregisterUser(OnComplete,
				OnTimeOut, OnError);
            function OnComplete(arg) { }
            function OnTimeOut(arg) { }
            function OnError(arg) { }

        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server" />


This is the final step: create a WebService that will be called from the JavaScript code, in order to remove the current user from the authenticated users' list. Don't forget to add the WebMethod(EnableSession = true) attribute to the UnregisterUser() method, otherwise it won't be able to reach the Session object.

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AuthenticatedUsersWebService : WebService
    /// <summary>
    /// Gets the System.Web.Caching.Cache object for the current application domain
    /// </summary>
    private Cache cache = HttpContext.Current.Cache;

    /// <summary>
    /// Removes the current user from the authenticated users' list
    /// </summary>
    [WebMethod(EnableSession = true)]
    public void UnregisterUser()
		string userName = Session["UserName"] != null ? 
			Session["UserName"].ToString() :   string.Empty;
		List<string> authenticatedUsers =   
				cache["AuthenticatedUsers"] != null 
			? (List<string> )cache["AuthenticatedUsers"]
			: new List<string>();
		if (authenticatedUsers.Contains(userName))   
		cache["AuthenticatedUsers"] =   authenticatedUsers;


  • [02.09.2009] First version
  • [02.19.2009] Fixed typo in AuthenticatedUsersMasterPage.Master
  • [02.25.2009] Fixed a bug in the authorization logic


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Gamil Méralli
Software Developer (Junior)
France France
No Biography provided

You may also be interested in...


Comments and Discussions

Generalsession Pin
Leo Rajendra Dhakal20-Jan-14 14:32
groupLeo Rajendra Dhakal20-Jan-14 14:32 
GeneralWeb Service Pin
MayChi3-Mar-10 4:36
memberMayChi3-Mar-10 4:36 
GeneralRe: Web Service Pin
Gamil Méralli3-Mar-10 6:07
memberGamil Méralli3-Mar-10 6:07 
GeneralRe: Web Service Pin
MayChi3-Mar-10 11:19
memberMayChi3-Mar-10 11:19 
GeneralRe: Web Service Pin
Gamil Méralli3-Mar-10 11:37
memberGamil Méralli3-Mar-10 11:37 
GeneralRe: Web Service Pin
MayChi4-Mar-10 4:32
memberMayChi4-Mar-10 4:32 
GeneralRe: Web Service Pin
Gamil Méralli4-Mar-10 6:18
memberGamil Méralli4-Mar-10 6:18 
QuestionIsOnline? Pin
kleinmk4-Mar-09 17:47
memberkleinmk4-Mar-09 17:47 
AnswerRe: IsOnline? Pin
Gamil Méralli4-Mar-09 23:27
memberGamil Méralli4-Mar-09 23:27 
Questionwebfarm/webgarden? Pin
ALGR2-Mar-09 17:02
memberALGR2-Mar-09 17:02 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 26 Feb 2009
Article Copyright 2009 by Gamil Méralli
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid