0

What should I do if someone tries to access page which is only allowed after being logged in to users. I have done this but it doesn't work, please help:

public ActionResult ViewMyAtdRecord()
{
    int EmplID = Convert.ToInt32(Session["Employee"]);

    if (Session["Employee"] == "")
    {
        ViewBag.Message = "NOT AUTHORIZED TO VIEW THIS PAGE";
        return View();
    }
    else 
    {
        IEnumerable<GetAtdRecord_SpResult> MyAtdRecord = DataContext.GetAtdRecord_Sp(EmplID).ToList();
        var names = (from n in DataContext.HrEmployees select n).Distinct();
        return View(MyAtdRecord);
    }
} 

Actually session begins here.

public ActionResult AfterLogIn(int EmplID, String EmpPwd) 
{
    int Num_Rows = (int)DataContext.GetUser_Pwd(EmplID, EmpPwd).First().No_Rows;
    if (Num_Rows == 1) 
    {
         Session["Employee"] = EmplID.ToString() ;
         ViewBag.Message = Session["Employee"];
    }
    else
    {
         ViewBag.Message = "Log-in Failed";
    }
    return View();
}
Andrei V
  • 7,306
  • 6
  • 44
  • 64
Evil rising
  • 442
  • 2
  • 7
  • 21

2 Answers2

4

First, avoid using session for storing authentication evidence. It makes you vulnerable to session fixation - someone can easily copy and reuse the contents of the ASP.NET_SessionId cookie, particularly if the site is accessible over HTTP and not HTTPS.

Use authentication cookies instead. Yes, cookies have some disadvantages, such as giving malicious users the ciphertext of your authentication cookie. However the FormsAuthenticationProvider has been developed with this in mind. This is why it is generally considered safer to use cookies.

Second, try to avoid using session at all. One of the huge advantages of ASP.MVC is the ability to run sessionless, allowing you to easily scale up your site if needed.

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47
1

I would recommend using FormsAuthentication (as suggested by @akton) and decorate the actions/controller with the Authorize attribute

If you want to go with Session rather than FormsAuthentication then you could try this out :

public ActionResult ViewMyAtdRecord()
{
    int empId = 0; 
    int.TryParse((string)Session["Employee"], out empId); // parse variable to int

    if (empId > 0) // we have an employee id, lets show that record.
    {
        IEnumerable<GetAtdRecord_SpResult> MyAtdRecord = DataContext.GetAtdRecord_Sp(empId ).ToList();
        var names = (from n in DataContext.HrEmployees select n).Distinct();
        return View(MyAtdRecord);
    }
    else // we do not have an employee id, show not authorized message.
    {
        ViewBag.Message = "NOT AUTHORIZED TO VIEW THIS PAGE";
        return View();
    }
} 
scheien
  • 2,457
  • 1
  • 19
  • 22