Reputation: 1547
Visual Studio 2010 - MVC 3
I have an admin section of an asp.net mvc application which I want to restrict access to. The application will not use accounts so I won't be using an administrator role or user to authorize access for example.
I want the section to be accessible by the entry of a single password. There will be a number of actions in this section. I have set up an admin controller which redirects to a number of different views so basically any view which this controller controls needs to be restricted.
I would also like it so that the password only needs to be entered once for a session, so when the browser is closed and reopened the password would need to be re-entered.
How would I achieve this?
Upvotes: 4
Views: 3970
Reputation: 75073
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:
[SimpleMembership]
SignIn
if not the correct onein 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.
Upvotes: 16
Reputation: 2752
I would use Forms authentication. and then add the [Authorize] attribute just to the controller or individual actions you want to restrict. Then you will need a way to log in ect. look Here for info on forms authentication hope that helps
You could always create your own authentication system saving the user name and password in a config file, or database or something. You can override the [Authorize] or create your own action filter and do with it as you wish.if you didn't want to get into the full forms authentication.
Upvotes: 1