Search code examples
asp.netasp.net-mvcsessionauthorizationasp.net-identity

Implement a Simple Authorization Function in ASP.NET Without Using ASP.NET Identity


I'm building a simple CMS using ASP.NET MVC 5 and Entity Framework 6. I have 2 sites: Public and Admin. Public site to diplay all the content and Admin site to manage all the content.

I only need a single Admin account to handle all the content in the Admin site. I'm thinking to use a session to keep the logged in user data and check for the session details when accessing an authorized page.

Keep the user data in a session.

var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();  
if (obj != null)  
{  
   Session["UserID"] = obj.UserId.ToString();  
   Session["UserName"] = obj.UserName.ToString();  
   return RedirectToAction("UserDashBoard");  
}  

Check before accessing an authorized page.

public ActionResult UserDashBoard()  
{  
     if (Session["UserID"] != null)  
     {  
         return View();  
     } else  
     {  
         return RedirectToAction("Login");  
     }  
 }  

So with this approach I wouldn't need to implement advance ASP Identity functions for the authorization.

Is this approach correct and would there be any downsides using this approach?


Solution

  • NEVER EVER EVER EVER EVER use session for authentication. It's insecure for starters, and it won't survive a loss of session (which IIS can kill at any time, for any reason). Session cookies are not encrypted, so they can be grabbed and used easily (assuming a non-encrypted link, even if you use HTTPS for authentication pages).

    Another issue is that you are doing your authentication way too late in the pipeline. OnAuthenticate runs at the very beginning of the pipeline, while you action methods are towards the end. This means that the site is doing a lot of work it doesn't have to do if the user is not authorized.

    I'm not sure why you are so against using Identity, the MVC basic templates already roll a full identity implementation for you. You don't have to do much.