【问题标题】:ASP.Net MVC 3 - Password Protect ViewASP.Net MVC 3 - 密码保护视图
【发布时间】:2012-09-04 21:34:37
【问题描述】:

Visual Studio 2010 - MVC 3

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

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

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

我将如何实现这一目标?

【问题讨论】:

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


    【解决方案1】:

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

    • 使用动作过滤器装饰控制器/动作,例如:[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 上的代码。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-07-10
        • 2011-05-10
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-28
        相关资源
        最近更新 更多