Question

I'm working on restricting access of static PDF files to only logged-in users. I only want to use a server-side redirect from the resource when a request comes that doesn't have the proper credentials.

I could use an IHttpHandler and set the path value, but I don't want to have to hand-serve the file. I would like requests from logged-in users to pass straight through, more like an IHttpModule, except I can't set a path to restrict the files that the module will act on.

Is there a way to pass requests through a handler, or limit the path of a module?

EDIT

It may also be useful to note that I want to redirect the user to a login page with a specific query string parameter redirecting the user back to the resource if login is successful.

Was it helpful?

Solution

If these are really static resources (exist on disk) then you could just stick them in a folder and restrict that folder using a location element in the web.config

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

This will prevent any unauthorized users from being able to access any files located in the MyPDFs folder within your site.

If you only want a subset of those files, then you can create a sub directory, and secure it in a similar fashion.

<location path="PDF/SecureSubDirectory">
   <system.web>
      <authorization>
         <deny users="?"/>
      </authorization>
   </system.web>
</location>

UPDATE:

It may also be useful to note that I want to redirect the user to a login page with a specific query string parameter redirecting the user back to the resource if login is successful.

This is all handled for you by default when using Forms Authentication in ASP.Net

Any request for a resource that fails because a user is not yet authenticated will automatically be redirected to the configured login page defined in your web.config.

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
    </forms>
  </authentication>
</system.web>

It appends a query string parameter that referes to the originally requested resource. Once the user successfully authenticates, they are redirected back to the URL they originally requested.

All this is baked into the framework :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top