Password protect a directory in IIS 7 (.Net MVC 2)

2019-08-21 02:40发布

问题:

I have a web application built in .NET MVC 2. I'd like to protect a directory with a password (basic authentication). In IIS 6, I'd simply go to the directory in security settings and remove anonymous.

But in IIS 7, I can't get it to work.

In the root of the website in authentication, I enabled anonymous because I want anyone to visit the website. Obviously.

Then I go to the MVC directory I want to protect (Views/Admin) and disable anonymous while enabling basic authentication. This doesn't work. I tried authorization rules but it didn't work either.

Is this because MVC uses sort of routing? I mean, the views/admin folder is actually website.com/admin which is, I suppose, kind of a virtual directory.

So, how to setup a password protected sub-directory in .NET MVC 2 on IIS 7?

Thanks

Stephane

回答1:

If someone stumbles upon this...

You need to add the AuthorizeAttribute to either your Controller to protect the whole thing or specific Action methods.

As described in the ASP.NET Tutorials, when this Attribute is encountered during the request, it will check to see if the user is properly authenticated and properly authorized in a role to access the Controller or Action. If not, it will request authentication from the user.