简体   繁体   中英

How to protect direct file access

I am building a webform application that only logged user can see certain pages.

Those pages contains links to several files, but once users know the full url (ex: " http://mywebsite.com/files/readme.txt ") they can access it any where any time without having to logged-in.

I use my custom authentication, I am not using asp.net provided security.

How can I prevent such problem, I am using asp.net C# 4.5 webform application, my hosting provider using IIS 7

Don't provide direct links to the files. Create a new page called GetFile.aspx?id=1 and have the page retrieve the files. That way the user never knows or has direct access to the files on your server. This way you can change security on the folder where your files exist so only the web server can access them directly.

Change your links on the page to be:

<a href="GetFile.aspx?id=1">Click here for read me file</a>

Example of how to download a file from asp.net:

public void DownloadFile(string fileName)
{
    Response.Clear();
    Response.ContentType = @"application\octet-stream";
    System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(FileName));
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(file.FullName);
    Response.Flush();
}

Code example taken from this question: Open any file from asp.net

Are you using any of the authentication schemes that provide ASP.Net (Windows,Forms,Passport)?

If yes, you could add to your Web.config file a 'location' section in which you can restrict the access for non-logged users to your file repository, something like this (based on your example):

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

In this case it doesn't matter if the user knows the full url address because it will not be available if it is offline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM