使用web.config文件在ASP.NET MVC 2中进行授权

dan*_*ani 4 authentication authorization web-config asp.net-mvc-2


我有一个ASP.MVC 2网页,我的身份验证完成如下:

FormsAuthentication.SetAuthCookie(user.UserName, false);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, "fooPage" + user.UserName, DateTime.Now, DateTime.Now.AddMinutes(10), false, String.Empty);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);  
Run Code Online (Sandbox Code Playgroud)

现在我想设置我的web.config,只有在用户通过身份验证时才能访问少量页面.我的web.config设置如下:

<configuration>  
  <system.web>  
    <authentication mode="Forms">  
      <forms loginUrl="~/Account/LogIn" timeout="2880"/> //all users can access my web site  
    </authentication>  
    <authorization>  
      <allow users="*"/>  
    </authorization>  
  </system.web>  
  <location path="~/Views/Sales/Index.aspx">  
    <system.web>  
      <authorization>  
        <deny users="?"/> //only authenticated users can access this page  
      </authorization>  
    </system.web>  
  </location>  
</configuration>  
Run Code Online (Sandbox Code Playgroud)

...但是这并不正常工作.

我究竟做错了什么?

Lev*_*evi 6

停止. 如果您尝试在Web.config中使用<location>来保护MVC应用程序,那么您最好让自己的生活变得困难,并且最糟糕的情况是在您的应用程序中打开一个巨大的安全漏洞.

正如Jon暗示的那样,使用[Authorize]或其他正确挂钩MVC管道(无论是声明性还是程序性)的东西是唯一正确的方法.产品团队在http://blogs.msdn.com/b/rickandy/archive/2010/08/24/securing-your-mvc-application.aspx上详细介绍了此问题.