Hi BugHunter,
In order to implement thisyou need to update the user SessionId in database after successfully login.
Then you need to check the page at every interval for same SessionId with the UserId.
If user try to access in different browser then the SessionId need to be validate. If the session is not same then redirect the user to the Login page.
Check this example. Now please take its reference and correct your code.
SQL
CREATE TABLE Users
(
UserId INT PRIMARY KEY NOT NULL,
Name VARCHAR(100) Not NULL,
Password VARCHAR(50) NOT NULL,
SessionId VARCHAR(100) NULL
)
INSERT INTO Users VALUES(1,'Dharmendra','12345','')
Namespaces
using System.Configuration;
using System.Data.SqlClient;
Controller
Login
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
public JsonResult UserLogin(LoginModel objLoginModel)
{
string returnVal = string.Empty;
string name = string.Empty;
try
{
if (objLoginModel != null)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT Name FROM Users WHERE UserId=@Id AND Password=@Password";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query);
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", objLoginModel.UserId);
cmd.Parameters.AddWithValue("@Password", objLoginModel.Password);
con.Open();
name = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (!string.IsNullOrEmpty(name))
{
Session["UserId"] = objLoginModel.UserId;
Session["Name"] = name;
query = "UPDATE Users SET SessionID = @Session WHERE UserId=@Id";
using (SqlConnection con1 = new SqlConnection(conString))
{
SqlCommand cmd1 = new SqlCommand(query);
cmd1.Connection = con;
cmd1.Parameters.AddWithValue("@Id", Session["UserId"]);
cmd1.Parameters.AddWithValue("@Session", Session.SessionID);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
}
returnVal = "success";
}
else
{
returnVal = "Invalid Password";
}
}
}
else
{
returnVal = "Internal Server Error !";
}
}
catch (Exception ex)
{
returnVal = "something went wrong.";
throw ex;
}
return Json(new { Response = returnVal });
}
}
Home
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
if (Session["UserId"] != null)
{
ViewBag.Name = Session["Name"];
return View();
}
else
{
return RedirectToAction("Index", "Login");
}
}
public JsonResult ValidateUser()
{
string returnVal = Session["UserId"] == null ? "failed" : string.Empty;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT SessionId FROM Users WHERE UserId=@Id";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query);
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", Session["UserId"]);
con.Open();
string id = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (id != Session.SessionID)
{
returnVal = "failed";
}
}
return Json(new { Response = returnVal });
}
}
View
Login
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript">
function SignIn() {
var userId = $('.userId').val();
var pswd = $('.password').val();
if (userId != null && pswd != null) {
var modelobject = {};
modelobject.UserId = userId;
modelobject.Password = pswd;
$.ajax({
data: modelobject,
type: "POST",
url: "/Login/UserLogin",
success: function (data) {
if (data.Response == 'success') {
location.href = "/Home/Index";
} else {
alert(data.Response);
}
},
failure: function (response) {
alert('Unable to process your request at this moment.Please try again later.');
},
error: function (response) {
alert('Unable to process your request at this moment. Please try again later.');
}
});
} else {
alert('Enter Valid User Id & Password');
}
}
</script>
</head>
<body>
<div style="text-align:right" class="container">
<table>
<tr>
<td>User Id :</td>
<td><input type="text" class="form-control userId" /></td>
<td>Password :</td>
<td><input type="text" class="form-control password" /></td>
<td><input type="button" id="btnLogin" onclick="return SignIn()" value="Login" class="btn btn-success" /></td>
</tr>
</table>
</div>
</body>
</html>
Home
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function () {
ValidateUser();
}, 1000)
function ValidateUser() {
$.ajax({
data: {},
type: "POST",
url: "/Home/ValidateUser",
success: function (data) {
if (data.Response == 'failed') {
location.href = "/Login/Index";
}
}
});
}
</script>
</head>
<body>
@if (ViewBag.Name != null)
{
<span>Welcome</span> @ViewBag.Name
}
</body>
</html>