Sunday, September 14, 2008

Document Security Over IIS Using Form Authentication

We all rely on asp.net authorization technique to protect our forms from anonymous access. But what about documents like pdf, images or other type of documents? By default, if anybody type the direct URL of a document in the browser’s address bar then IIS6 permit them to see the physical document without checking the authentication permission. Its a big threat for secured web-site. To solve the issue, we have to configure IIS such a way so that aspnet_isapi.dll take the control to show the document while request will come. Here is what it can be done:

1. Right click on the virtual directory which need to be secured and select property. From the opened dialogue box select Virtual Directory tab and click on configuration button. Now add a new configuration with the following settings

Executable: aspnet_isapi.dll location

Extension: document extension (like .pdf)

Verbs: GET

clip_image001

2. Add Location path to web.config file

<location path="temp-pdf">

    <system.web>

      <authorization>

        <deny users="?" />

      </authorization>

    </system.web>

  </location>

That’s it. You are done. Now if you want that the document will be handle by custom code for extra security then you can add a entry in the http handler in the following way:

1. Add a entry to httphandlers section to handle the file type for extra security in web.config file

 

<httpHandlers>

      <add verb="*" path="*.pdf" type="PdfHandler" validate="false"/>

</httpHandlers>

2. And create a custom class to App_Code following way:

Public Class PdfHandler

    Implements IHttpHandler

 

    Public Sub New()

    End Sub

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim path As String = context.Request.PhysicalPath

        Dim name As String = path.Split("\"c)(path.Split("\"c).Length - 1)

        If Not String.IsNullOrEmpty(path) AndAlso path.ToLower().EndsWith(".pdf") Then

            context.Response.ClearHeaders()

            context.Response.ClearContent()

            context.Response.Clear()

 

            context.Response.Charset = Nothing

            context.Response.ContentType = "application/pdf"

            context.Response.AddHeader("Content-Type", "application/pdf")

            context.Response.AppendHeader("Content-Disposition", String.Format("inline;filename={0}", name))

            context.Response.WriteFile(path)

        Else

            Throw New FileNotFoundException("The page requested is invalid", path)

        End If

    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property

End Class

 

Note: You can replace the above code with your custom requirements.

Happy Programming!

No comments: