Prevent multiple systems Login using same User Name and Password in ASP.Net

Last Reply 20 days ago By pandeyism

Posted 21 days ago

hello,

i am using this snippet it works wornderful

Keep User Logged in and automatically Login User using Forms Authentication and Cookies in ASP.Net 

i am in a sitution for which it fails

user Bob log in with his id and pass word on Device 1

if same userid Bob is try to login to Device 2 so same user id is now running on two Devices which is wrong. i want if Bob is login in Device 1 and same userid is try to login on Device 2 so Device 1 user id should automatically logout please advice

Posted 20 days ago

Hi nauna,

When you click on login button user will validate if user exist or not.

And then you will have to create a table where you have store login details of user like ip address of user machine and username or id and login date.

And then by user id or username get ip addres from table, if ip address is there then it is going to check current ip address with getting ip address from table.

if they are similar then it is going to be logging. Else if it is not similar then it is going to update current ip address and logging date in table.

And then it is going to logging bases on current ip address.

When you click on Logout you need to remove the record from database.

Refer below sample.

HTML

Login.aspx

<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser">
</asp:Login>

Home.aspx

<div>
    Welcome
    <asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
    <br />
    <br />
    <asp:Label ID="lblLastLoginDate" runat="server" />
    <asp:LoginStatus ID="LoginStatus1" runat="server" 
        onloggedout="LoginStatus1_LoggedOut" />
</div>

Namespaces

C#

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;

VB.Net

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security

Code

C#

Login.aspx.cs

protected void ValidateUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Validate_User"))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Username", Login1.UserName);
            cmd.Parameters.AddWithValue("@Password", Login1.Password);
            cmd.Connection = con;
            con.Open();
            userId = Convert.ToInt32(cmd.ExecuteScalar());
        }
        switch (userId)
        {
            case -1:
                Login1.FailureText = "Username and/or password is incorrect.";
                break;
            case -2:
                Login1.FailureText = "Account has not been activated.";
                break;
            default:
                string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(ipAddress))
                {
                    ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                }
                string constr1 = ConfigurationManager.ConnectionStrings["constr1"].ConnectionString;
                SqlConnection con1 = null;
                SqlCommand cmd1 = null;

                string getIp = getIpAddress(Login1.UserName);

                if (!string.IsNullOrEmpty(getIp))
                {
                    if (ipAddress != getIp)
                    {
                        con1 = new SqlConnection(constr1);
                        cmd1 = new SqlCommand("UPDATE tblSession SET ipAddress = @ipAddress ,LoginDate =@LoginDate WHERE UserName = @UserName", con1);
                        cmd1.Parameters.AddWithValue("@ipAddress", ipAddress);
                        cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now);
                        cmd1.Parameters.AddWithValue("@UserName", Login1.UserName);
                        con1.Open();
                        cmd1.ExecuteNonQuery();
                    }
                    else
                    {
                        con1 = new SqlConnection(constr1);
                        cmd1 = new SqlCommand("UPDATE tblSession SET LoginDate =@LoginDate WHERE UserName = @UserName", con1);
                        cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now);
                        cmd1.Parameters.AddWithValue("@UserName", Login1.UserName);
                        con1.Open();
                        cmd1.ExecuteNonQuery();
                    }
                }
                else
                {
                    con1 = new SqlConnection(constr1);
                    cmd1 = new SqlCommand("INSERT INTO tblSession VALUES(@ipAddress,@UserName,@LoginDate)", con1);
                    cmd1.Parameters.AddWithValue("@ipAddress", ipAddress);
                    cmd1.Parameters.AddWithValue("@UserName", Login1.UserName);
                    cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now);
                    con1.Open();
                    cmd1.ExecuteNonQuery();
                    con1.Close();
                }
                FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
                break;
        }
    }
}

public string getIpAddress(string userName)
{
    string constr = ConfigurationManager.ConnectionStrings["constr1"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("SELECT ipAddress FROM tblSession WHERE UserName = @UserName", con);
    cmd.Parameters.AddWithValue("@UserName", userName);
    con.Open();
    string ipAddress = Convert.ToString(cmd.ExecuteScalar());
    con.Close();
    return ipAddress;
}

Home.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}

protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr1"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("DELETE FROM tblSession WHERE UserName = @UserName", con);
    cmd.Parameters.AddWithValue("@UserName", this.Page.User.Identity.Name);
    con.Open();
    string ipAddress = Convert.ToString(cmd.ExecuteScalar());
    con.Close();
}

VB.Net

Login.aspx.vb

Protected Sub ValidateUser(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim userId As Integer = 0
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Using cmd As SqlCommand = New SqlCommand("Validate_User")
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@Username", Login1.UserName)
            cmd.Parameters.AddWithValue("@Password", Login1.Password)
            cmd.Connection = con
            con.Open()
            userId = Convert.ToInt32(cmd.ExecuteScalar())
        End Using

        Select Case userId
            Case -1
                Login1.FailureText = "Username and/or password is incorrect."
            Case -2
                Login1.FailureText = "Account has not been activated."
            Case Else
                Dim ipAddress As String = Request.ServerVariables("HTTP_X_FORWARDED_FOR")

                If String.IsNullOrEmpty(ipAddress) Then
                    ipAddress = Request.ServerVariables("REMOTE_ADDR")
                End If

                Dim constr1 As String = ConfigurationManager.ConnectionStrings("constr1").ConnectionString
                Dim con1 As SqlConnection = Nothing
                Dim cmd1 As SqlCommand = Nothing
                Dim getIp As String = getIpAddress(Login1.UserName)

                If Not String.IsNullOrEmpty(getIp) Then

                    If ipAddress <> getIp Then
                        con1 = New SqlConnection(constr1)
                        cmd1 = New SqlCommand("UPDATE tblSession SET ipAddress = @ipAddress ,LoginDate =@LoginDate WHERE UserName = @UserName", con1)
                        cmd1.Parameters.AddWithValue("@ipAddress", ipAddress)
                        cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now)
                        cmd1.Parameters.AddWithValue("@UserName", Login1.UserName)
                        con1.Open()
                        cmd1.ExecuteNonQuery()
                    Else
                        con1 = New SqlConnection(constr1)
                        cmd1 = New SqlCommand("UPDATE tblSession SET LoginDate =@LoginDate WHERE UserName = @UserName", con1)
                        cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now)
                        cmd1.Parameters.AddWithValue("@UserName", Login1.UserName)
                        con1.Open()
                        cmd1.ExecuteNonQuery()
                    End If
                Else
                    con1 = New SqlConnection(constr1)
                    cmd1 = New SqlCommand("INSERT INTO tblSession VALUES(@ipAddress,@UserName,@LoginDate)", con1)
                    cmd1.Parameters.AddWithValue("@ipAddress", ipAddress)
                    cmd1.Parameters.AddWithValue("@UserName", Login1.UserName)
                    cmd1.Parameters.AddWithValue("@LoginDate", DateTime.Now)
                    con1.Open()
                    cmd1.ExecuteNonQuery()
                    con1.Close()
                End If

                FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
                Exit Select
                con.Close()
        End Select
    End Using
End Sub

Public Function getIpAddress(ByVal userName As String) As String
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr1").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("SELECT ipAddress FROM tblSession WHERE UserName = @UserName", con)
    cmd.Parameters.AddWithValue("@UserName", userName)
    con.Open()
    Dim ipAddress As String = Convert.ToString(cmd.ExecuteScalar())
    con.Close()
    Return ipAddress
End Function