skylake skylake - 2 months ago 12
C# Question

Allow user to visit [Authorize] pages - MVC

My project got pages with

[Authorize]
where user have to log in to visit those pages.

Upon successful login with same userid and password as in database, the current users id get stored in session. But how do I do I authenticate/allow user to visit pages with [Authorize]?

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User u)
{

if (ModelState.IsValid) //this is check validity
{

using (UserEntities db = new UserEntities())
{

var v = db.Users.Where(a=>a.UserName.Equals(u.UserName) && a.Password.Equals(u.Password)).FirstOrDefault();
if (v != null)
{
Session["LoggedUserID"] = v.Id.ToString();
Session["LoggedUserFullname"] = v.FirstName.ToString();

return RedirectToAction("AfterLogin");

}

}
}
return View(u);
}


Any help is much appreciate. Thanks.

Answer

If you absolutely want to manage login and security yourself using Session, You can create your own action filter which checks whether session has a user id set to it.

Something like this

public class AuthorizeWithSession : ActionFilterAttribute
{       
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.HttpContext.Session == null ||
                                      context.HttpContext.Session["LoggedUserID"]==null)
        {
            context.Result =
                new RedirectToRouteResult(new RouteValueDictionary(
                                     new {controller = "Account", action = "Login"}));
        }
        base.OnActionExecuting(context);
    }
}

Now decorate this action filter on your secure actions/controllers

[AuthorizeWithSession]
public class TeamController : Controller
{
}
Comments