I have some files in my Content folder that I don't want a user to be able to download without being authorised. How do I prevent a user from just getting to the file by typing ...Content/{filename} into the address bar?
3 Answers
There are a couple of possibilities. The first one consists into using the <location>
tag in your web.config:
<location path="Content">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
Another possibility is to put those files inside a folder where noone can access (like the App_Data folder for example) and then have a controller action that will serve those files which will be decorated with the [Authorize]
attribute.

- 1,023,142
- 271
- 3,287
- 2,928
-
Where would this be located in the web.config? – user517406 May 29 '12 at 08:07
-
Inside the `
` element and outside ` – Darin Dimitrov May 29 '12 at 08:08`. It's at the root. -
1OK thanks, didn't get it working straight away as it should be
not :) – user517406 May 29 '12 at 08:13 -
Yes I made a mistake. You are correct: `
` should be used. I have updated the answer. – Darin Dimitrov May 29 '12 at 08:18
Well one way is to have it outside the context of IIS, so instead of having them under C:\inetpub\wwwroot
change it to something like C:\temp\files
.
in your DB have a GUID associated with the document name and use the GUID to display the link to the file.
in your controller action you would just accept the GUID, get the filename and then serve the file in your response.

- 2,078
- 1
- 29
- 41
it doesn't work for me.
<configuration>
<appSettings>
...
</appSettings>
<system.web>
...
</system.web>
<system.webServer>
...
</system.webServer>
<location path="Content">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
I run my MVC 4.0 application, login and logout, can't access any app page, but still can access file by direct link like
http://localhost:80966/Content/Files/home.jpg

- 1,969
- 4
- 25
- 30