Simple download protection for files and document using ASP.NET / C#

Posted in .NET 2.0 | Authentication | Security at Monday, December 24, 2007 2:36 PM GMT Standard Time
Really really simple. Feel free to write your own custom authentication method to fit your project context.

This is download.aspx:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="download.aspx.cs" Inherits="download" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Download Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

and this is the code behind that file:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class download : System.Web.UI.Page 
{

    /// 
    /// Show error to user and close response object.
    /// 
    /// 
    private void WriteError(string error) {
        Response.Write(error);
        Response.End();
    }

    /// 
    /// Check authentication ticket
    /// 
    /// 
    private bool Authenticated() {
        //whatever is a session ticket, membership provider base, container in a coded URL querystring parameters, etc..
        return true;    
    }

    private string GetRepositoryFolder() {
        System.Configuration.AppSettingsReader r = new AppSettingsReader();
        return r.GetValue("RepositoryFolder", typeof(string)).ToString();                
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Authenticated()){
            WriteError("You are not allowed to download this file");
            return;
        }
        else if (Request.QueryString["id"] == null)
        {
            WriteError("Missing parameter : id");
            return;
        }       
        
        string filePath = System.IO.Path.Combine(GetRepositoryFolder(),Request.QueryString["id"]);
        System.IO.FileInfo file = new System.IO.FileInfo(filePath);
        if (!file.Exists)
        {
            WriteError("File doesn't exists");
            return;
        }
        else {
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            Response.End();
        }        
    }
}
If successfully authenticated, you will be able to directly download the file:


If not, you will get an error message:

You are not allowed to download this file

AddThis Social Bookmark Button