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

时间:2012-09-11 21:50:29

标签: asp.net asp.net-mvc passwords

Visual Studio 2010 - MVC 3

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

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

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

我将如何实现这一目标?

2 个答案:

答案 0 :(得分:16)

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

  • 使用操作过滤器修饰控制器/操作,例如:[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);
        }
    }
}

和您的控制器

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();
    }
}

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


源代码:

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

答案 1 :(得分:1)

我会使用Forms身份验证。 然后将[Authorize]属性添加到控制器或您要限制的单个操作。 然后你需要一种登录方式。 查看表单身份验证信息Here希望有帮助

您始终可以创建自己的身份验证系统,在配置文件或数据库或其他内容中保存用户名和密码。您可以覆盖[授权]或创建自己的操作过滤器,并根据需要使用它。如果您不想进入完整的表单身份验证。