-1

I have a website that Contains pdf files stored in folder on server and i need to set access to this files in folder only for users that logged in and belong to role i choose! thanks for helping :) :)

Explain the situation: name of folder is "files" name of a file in folder is "f.pdf" when i type this url "www.website.com/files/f.pdf" it's open pdf file that suppose open only for authenticated users?? how can i solve this problem ??

Hassan Juniedi
  • 403
  • 5
  • 14
  • What have your tried already? – Middas Mar 07 '13 at 04:31
  • in database i have membership table and role table .. and evrey thing is ok with pages put with files i have problem to show them only for users in role – Hassan Juniedi Mar 07 '13 at 04:35
  • If you're using the standard membership database then you're not depending on anything that defines this behavior for you (like Windows Authentication does). You'll need to maintain your own cross reference of membership groups/users to files to ensure that only users with permission are allowed to access the files you want them to. The problem... your web app is not the logged in user so you need to enforce this yourself. – M.Babcock Mar 07 '13 at 05:05
  • thanks for replay but how can i do this? – Hassan Juniedi Mar 07 '13 at 05:11
  • Break it up into its constituent parts: You need to learn how to check file permissions (the user your app is running as better have god-like abilities) for a specific user or just depend on custom fake database file permissions (not recommended). Sit down for 15 minutes and think through the scenarios you need to cover and what all will need to be involved... in the end you'll figure it out. – M.Babcock Mar 07 '13 at 05:53

1 Answers1

2

Move the folder outside of the root, or place it is a protected folder like App_Data to prevent direct browsing. Then create a "handler" page that can authenticate the user and serve the file. The code in the handler would look something like this:

@{
    WebSecurity.RequireAuthenticatedUser();
    var file = Request["file"];
    if(Path.GetFileExtension(file).Equals(".pdf")){
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=" + file);
        Response.WriteFile(Server.MapPath("~/App_Data/PDF/" + file);
    }
}

In your page, you just need to provide a standard link, but the href should point to the handler and the file name added to a query string:

<a href="~/handler.cshtml?file=myPdf.pdf">Click to download</a>
Mike Brind
  • 28,238
  • 6
  • 56
  • 88