ASP.NET provides the funtionality of securing many
different files which include .aspx, .resources, .config etc. You can place the
files inside a folder and make few adjustments in the web.config and that is it.
Now, your files are secured for malacious users.
Below is a small configuration that enables the protection on the files
contained in the MySecureFolder.
<location path="MySecureFolder">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
The access to MySecureFolder is denied to all anonymous
users. But if you place a pdf or a zip file inside the MySecureFolder you will
be able to download it simply by typing the path in the url. This is because
ASP.NET does not provide protection to these files. So how do we protect it?
Well, you can provide a simple HttpHanlder that will check for the requested
file and if the user is authenticated then allows to download the file. Here is
a simple HttpHandler called ZipFileHandler.
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;
using System.IO;
using GridViewGuyBusinessLogic;
public class ZipFileHandler :IHttpHandler
{
public ZipFileHandler()
{
}
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
if (!context.User.Identity.IsAuthenticated)
{
context.Response.Redirect("~/Login.aspx");
context.Response.StatusCode = 401;
return;
}
string url = (context.Request.CurrentExecutionFilePath);
try
{
DownloadManager.Download(url);
}
catch (Exception ex)
{
context.Response.StatusCode = 404;
}
}
}
And here is the code for the DownloadManager.Download method:
// this method is used to download the file from the server folder
public static void DownloadFile(string url)
{
string fileName = String.Empty;
string filePath = String.Empty;
if (!String.IsNullOrEmpty(url))
{
filePath = HttpContext.Current.Server.MapPath(url);
fileName = System.IO.Path.GetFileName(filePath);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AddHeader("Content-Disposition",
"inline; filename=" + fileName);
HttpContext.Current.Response.WriteFile(filePath);
HttpContext.Current.Response.End();
}
}
You can also call the DownloadManager.Download method when you click on the
LinkButton to download the file. I said LinkButton and not Hyperlink that is
because HyperLink displays the location of the file and the LinkButton does
not.
If you want more security then you can contact your ISP and they can password
protected your folder. You can even do this by yourself by going to the control
panel of your ISP.
powered by IMHO 1.3