Delmonte
Delmonte

Reputation: 411

How to allow access to a web folder only to authenticated users

My web application uses forms authentication mode.

<authentication mode="Forms">
  <forms loginUrl="Logon.aspx" protection="All" path="/" timeout="60" slidingExpiration="false" />
</authentication>

<authorization>
  <deny users="?"/>
</authorization>

There is a folder in my web application, named "Documentos", that has a lot of PDF files.

My program allow the user to load a PDF file using its URL address:

http://MyHost/MyWebApp/Documentos/1.pdf

However, I need to restrict that functionality only to authenticated users.

For that, I put in my web.config:

  <location path="Documentos">
      <system.web>
          <authorization>
              <deny users="?" />
          </authorization>
      </system.web>
  </location>

But it doesn't make any difference. Any one can still load any PDF file in folder Documentos doing:

http://MyHost/MyWebApp/Documentos/1.pdf

Can I accomplish what I'm looking for or should I approach it in a different way?

EDIT

Win's solution and Richard's solution are correct. This is the way to put those settings in web.config:

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>
  <location path="Documentos">
        <system.web>
            <authorization>
                <deny users="?" />
            </authorization>
        </system.web>
  </location>  

Upvotes: 0

Views: 2815

Answers (2)

Richard
Richard

Reputation: 30618

The problem is that by default, the auth section only applies to requests that go through the pipeline, not to static files. To do what you want, add the following attribute to your modules section:

<system.webServer>   
  <modules runAllManagedModulesForAllRequests="true">
...

Upvotes: 1

Win
Win

Reputation: 62260

Yo have two options -

Option 1

Use ~/ if your web application is not root level.

<location path="~/Documentos">
      <system.web>
          <authorization>
              <deny users="?" />
          </authorization>
      </system.web>
  </location>

Option 2

Create a web.config with following content, and place it inside Documentos folder.

<?xml version="1.0"?>
<configuration>

  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

</configuration>

Upvotes: 2

Related Questions