Saturday, April 2, 2011

How to prevent cross site image reference by HTTP Handler in ASP.NET

http://www.blackbeltcoder.com/Articles/asp/writing-a-custom-http-handler-in-asp-net


This is a very simple handler that starts by seeing if the request came from the current domain. If not, HTML markup for an "Access Denied" message is constructed and returned.
Custom HTTP Handler
using System;
using System.Globalization;
using System.Web;

public class JpgHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;

        // Try and prevent request from a different domain
        if (request.Url != null && request.UrlReferrer != null)
        {
            if (String.Compare(request.Url.Host, request.UrlReferrer.Host,
                true, CultureInfo.InvariantCulture) != 0)
            {
                response.Write("<html>\r\n");
                response.Write("<head><title>JPG HTTP Handler</title></head>\r\n");
                response.Write("<body>\r\n");
                response.Write("<h1>Access Denied</h1>\r\n");
                response.Write("</body>\r\n");
                response.Write("</html>");
                return;
            }
        }

        // Otherwise transfer requested file
        try
        {
            response.ContentType = "application/jpg";
            response.WriteFile(request.PhysicalPath);
        }
        catch
        {
            response.Write("<html>\r\n");
            response.Write("<head><title>JPG HTTP Handler</title></head>\r\n");
            response.Write("<body>\r\n");
            response.Write("<h1>Access Granted but file was not found</h1>\r\n");
            response.Write("</body>\r\n");
            response.Write("</html>");
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }
}


Web.config File
<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0"/>
    </system.web>
    <system.webServer>
        <handlers>
            <add verb="*" path="*.jpg" name="JpgHttpHandler" type="JpgHttpHandler"/>
        </handlers>
    </system.webServer>
</configuration>


No comments:

Post a Comment