ASP.Net MVC 3 - 密码保护 View

标签 asp.net asp.net-mvc passwords

Visual Studio 2010 - MVC 3

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

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

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

我将如何实现这一目标?

最佳答案

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

  • 用 Action 过滤器装饰 Controller / Action ,例如:[SimpleMembership]
  • 在该操作过滤器上,只需检查 session 变量
  • 的存在和内容
  • 重定向到 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);
            }
        }
    }
    

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

    如果你想装饰整个controller ,您需要移动 SignIn外面的方法到达那里,你需要进行身份验证。

    源代码:

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

    关于ASP.Net MVC 3 - 密码保护 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12378445/

    相关文章:

    c# - 如何读取多个文件txt c#

    c# - 如何在 ASP.net/C# 应用程序配置文件值中为值添加一个符号

    javascript - 从更新面板调用 javascript 不起作用

    c# - Post请求为空(ASP.NET Core)

    security - 什么更安全?我应该向用户发送包含过期 URL 的电子邮件以重置其密码,还是应该通过电子邮件发送新生成的密码?

    .net - 使用 jQuery 的 ASP.NET Webforms?

    asp.net-mvc - WIF 不适用于 ASP.NET MVC 4

    asp.net-mvc - ASP.net 5 MVC 6 bower.json 和 project.json 消失

    java - psql cmd命令指定密码(通过java应用程序)

    ant - 使用 Apache ant 解压缩受密码保护的 zip 文件?