Assuming that you have a View folder called Protected (as your controller), and you have several Actions that points to several Views, I would do this:
- decorate the controller/actions with an Action Filter, for example:
[SimpleMembership]
- on that action filter, just check the existence and the contents of a Session Variable
- redirect to a
SignIn if not the correct one
in code:
public class SimpleMembershipAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//redirect if not authenticated
if (filterContext.HttpContext.Session["myApp-Authentication"] == null ||
filterContext.HttpContext.Session["myApp-Authentication"] != "123")
{
//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = "/Protected/SignIn" + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
and your controller
public class ProtectedController : Controller
{
[SimpleMembership]
public ActionResult Index()
{
return View();
}
public ActionResult SignIn()
{
return View();
}
[HttpPost]
public ActionResult SignIn(string pwd)
{
if (pwd == "123")
{
Session["myApp-Authentication"] = "123";
return RedirectToAction("Index");
}
return View();
}
}
if you want to decorate the entire controller, you need to move the SignIn methods outside as to reach there, you would need to be authenticated.
Source code:
You can download the simple MVC3 solution http://cl.ly/JN6B or fell free to view the code on GitHub.