I have an ASP.MVC 2 web page and I have my authentication done like this:
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);
Now I would like to set my web.config in a way that few pages can be only accessed if a user is authenticated. I have my web.config set like this:
<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>
… but this does not work.
What am I doing wrong?
It’s much easier to put the
[Authorize]attribute on the controller action:You can also put the attribute on the controller instead of having to put it on every action method…
Edit in response to your comment: I don’t know that it’s possible to do natively using XML, but check out http://www.jigar.net/articles/viewhtmlcontent324.aspx
Second edit, I’ve done some research and testing, and it is possible to use the default ASP.NET web.config stuff, use
<location path="~/Sales/Index">instead of<location path="~/Views/Sales/Index.aspx">BUT
you have to be really really careful if there’s more than one URL that could land you on the same page, such as
/,/Home,/Home/,/Home/Index, etc – you won’t get the authorization settings on all of them automatically. I think it’s much safer to use something MVC-aware, such as the[Authorize]attribute, or the custom scheme I linked to above.