ASP.Net MVC 3 - 密码保护视图

Jpi*_*pin 4 asp.net passwords asp.net-mvc

Visual Studio 2010 - MVC 3

我有一个asp.net mvc应用程序的管理部分,我想限制访问.应用程序不会使用帐户,因此我不会使用管理员角色或用户来授权访问权限.

我希望通过输入单个密码来访问该部分.本节将介绍一些操作.我已经设置了一个管理控制器,它可以重定向到许多不同的视图,因此基本上任何需要限制该控制器控制的视图.

我也希望它只需要为会话输入一次密码,因此当浏览器关闭并重新打开时,需要重新输入密码.

我怎么做到这一点?

bal*_*dre 16

假设您有一个名为Protected(作为您的控制器)的View文件夹,并且您有几个指向多个视图的操作,我会这样做:

  • 使用Action Filter装饰控制器/操作,例如: [SimpleMembership]
  • 在该动作过滤器上,只需检查会话变量的存在和内容
  • 重定向到一个SignIn如果不是正确的

在代码中:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

和你的控制器

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想装饰整个方法controller,你需要将SignIn方法移到外面以便到达那里,你需要进行身份验证.


源代码:

您可以下载简单的MVC3解决方案http://cl.ly/JN6B或免费查看GitHub上的代码.