Humaira
Humaira

Reputation: 51

Render PDF Files at client side without exposing original path to prevent download

Current possible way to Restrict Direct Access to files is placing in App_Data folder. But if i use app_data folder it will block direct browser access as well as rendering in HTML. I want to allow files in App_Data programmatically to render at Client side with some sort of Authorization i.e: Session value

Right now if I move uploaded files to other folders and render in html it will work but it will also expose direct access to files which is not required & in my scenario is a security loop hole.

What I have tried so far 1. I have achieved restricting file download via direct url. Using FileResult Method. But i am still unable to render files in client side (Jquery).

Upvotes: 1

Views: 351

Answers (2)

Mohiyo Deen
Mohiyo Deen

Reputation: 137

I have also faced same scenario, After searching I came up with this solution from this answer.

https://stackoverflow.com/a/10604182/5934624

Using this answer all I have to create an IHTTPHANDLER to intercept all the requests being sent to App_Data or any folder you want to secure.

IHTTPHANDLER

    public class PdfHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }
        public void ProcessRequest(HttpContext context)
        {
            /*
                Validate Requests here and then return your PDF File
            */
            var requestFilePath = context.Requests.AppRelativeCurrentExecutionFilePath;
            context.Response.ContentType = "application/pdf";
            string filePath = HttpContext.Current.Server.MapPath(path);
            context.Response.TransmitFile(filePath);
        }
    }

Also add reference in Web.Config

<system.webServer>
  <handlers>
    <add name="cplFiles" verb="*" path="*.pdf" type="YourProject.Models.PdfHandler , YourProject" resourceType="File" />
  </handlers>
</system.webServer>

Upvotes: 1

Mostafa Mohamed Ahmed
Mostafa Mohamed Ahmed

Reputation: 649

one way would be returning the file as a byte[] (or any other format) then re-construct or re-create the file at the client side from this bye []

u can also create a temp location that is accessible for the client , copy the file there and serve it from there , delete the file after it's been served (of course not best practice when it comes to performance but it's very good security wise because a specific URL won't work twice )

Upvotes: 0

Related Questions