Arcadian
Arcadian

Reputation: 4350

How to secure a document/pdf request in MVC?

I am wondering what is the preferred practice to secure document.

If I have a link in my page like:

option 1)   http://myserver/documents/mydoc.pdf

can I secure it using a filter to check if the user is logged in or has the correct role?

my first thinking was to create an action call ViewDoc. In ViewDoc I would check the permissions etc and then read the file in and send it to the response.

so my request would look something like this:

option 2)    http://myserver/mycontroller/ViewDoc/17

If I go with option 2, do I need to have my files outside the web folder? If I have in the web folder, could a user make a request directly to the file? any other options or suggestions?

Upvotes: 2

Views: 1113

Answers (2)

Fals
Fals

Reputation: 6839

Just return the Document througt a Action with the Authorize attribute:

[Authorize]
public ActionResult GetFile(string filename)
{
  //get the file somewhere
  return return File(file, "contentType");
}

Upvotes: 1

Nate
Nate

Reputation: 30636

Your proposed solution is the correct way to do this.

You will use a FileResult action (unless you have good reason not to) and in that action you will probably use [Authorize] and perform any business logic necessary to validate the user should be reading it. Then you return the file using the controller's File() function.

[Authorize]
public FileResult ViewDoc(int id)
{
    // do things, maybe lookup file path of document from database
    return File(pathToYourFile, "document/pdf", "downloadedFileName.pdf");
}

Upvotes: 2

Related Questions