Checking for logged in user using jQuery in ASP.NET

Sheonarayan
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 6443 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article, we shall learn how to check if a user is logged into the application using jQuery to perform some client side operation.
Recommendation
Read Forms Authentication in ASP.NET with C#: Basic before this article.

Introduction


There was a Forums posts asking for how to check for the user Session, if a user is logged in. Even if there is no need to check for Session object to ensure that user is logged in as it can be done using alternative better way. However, I thought lets write an article for this as this is very frequently asked question in the Forums.


Objective


The objective of this article is to check if a user is logged in using client side script (JavaScript/jQuery) before performing some member specific article in the browser.

Page that show if user is logged in


Here is my simple page that checks if user is logged in and shows a true/false alert based on user's logged in status.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <title></title>

      <script type="text/javascript">
          $.get("test.aspx?checkForLogin=1", "", function (result) {
              alert(result);
            // if true, perform member specific operation otherwise show appropriate message
          });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
In the above code snippet; as soon as page loads, a ajax get request is sent to test.aspx page with a querystring (checkForLogin) and whatever is returned form the test.aspx is shows as alert message to the browser.

Checking for user log in and returning status


In the test.aspx.cs page, I have following code snippet in the Page_Load event
Note that my test.aspx.cs page is completely blank except the Page directive.

Test.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
Test.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["checkForLogin"]))
        {
            Response.ClearHeaders();
            Response.ClearContent();
            Response.Clear();
            if (User.Identity.IsAuthenticated)
            {
                Response.Write("true");
            }
            else
            {
                Response.Write("false");
            }
        }
    }

In the above code snippet, I am checking for the checkForLogin querystring and checking if user is authenticated using User.Identity.IsAuthenticated property and returning true, if yes otherwise false if no.

The same value is returned as result to the page from where test.aspx page is being called.

The querystring checkForLogin was not required but we have kept it as we wanted to use the .aspx page for other purpose also. If the purpose of test.aspx is only to determine if your is logged in, we can remove the querystring condition.

Point of Interest - Correct way to implement Login functionality


It is a general practice by beginner developer to set a Session value if the username and password match in the database and check for that Session value on every page to ensure that user is logged in. Even if this process solve its purpose but this is not the right way and it is prone to error if the application is kept idle for sometime and session expires. The correct way to implement login functionality in ASP.NET is explained in this article "Forms Authentication in ASP.NET with C#: Basic"

Conclusion


In this article, we learnt how to check the user login status using jQuery ajax method without refreshing the page and also understood the best way to implement login functionality in ASP.NET.

Thanks for reading the article, do subscribe for RSS feed to get new article notification in Inbox.
Recommendation
Read Forms Authentication in ASP.NET with C#: Advance after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)