Click here to Skip to main content
13,767,441 members
Click here to Skip to main content
Add your own
alternative version


73 bookmarked
Posted 19 Mar 2006

Secure File Download Using Basic Authentication

Rate this:
Please Sign up or sign in to vote.
Secure file download using Basic Authentication. The interesting part is that we maintain two separate entry points for uploading and downloading a file.

Sample Image - Secure_File_Download.jpg


Security has always been a top issue for all kinds of applications, especially Web applications. Web apps are accessible to almost the entire universe, and are open to attack. Most of the web applications provide the file download feature, the real time challenge is not in providing such a feature, but in securing such operations. Recently, I dealt with an application which demands for secure file upload and download, during which I did wide research, so I thought of sharing it with the world to make it worth.

You may find several articles on the internet talking about secure downloads, but this article is a bit different from all those, because it distinguishes between upload and download by providing two different entry points for them.

The following article depicts how secured file download can be achieved using IIS basic authentication.


Before we start, let's refresh our memory and learn some basics.

An ASP.NET application has two separate authentication layers. That is because ASP.NET is not a standalone product. Rather, it is a layer on top of IIS. All requests flow through IIS before they are handed to ASP.NET. As a result, IIS can decide to deny access without the ASP.NET process even knowing that someone requested a particular page. Here is an overview of the steps in the joint IIS and ASP.NET authentication process:

  1. IIS first checks to make sure the incoming request comes from an IP address that is allowed access to the domain. If not, it denies the request.
  2. Next, IIS performs its own user authentication if it is configured to do so. By default, IIS allows anonymous access, so requests are automatically authenticated, but you can change this default on a per – application basis within IIS.
  3. If the request is passed to ASP.NET with an authenticated user, ASP.NET checks to see whether impersonation is enabled. If impersonation is enabled, ASP.NET acts as though it were the authenticated user. If not, ASP.NET acts with its own configured account.
  4. Finally, the identity from step 3 is used to request resources from the operating system. If ASP.NET authentication can obtain all the necessary resources, it grants the user's request, otherwise it is denied. Resources can include much more than just the ASP.NET page itself. You can also use .NET’s code access security features to extend this authorization step to disk files, Registry keys, and other resources.

How it works

In general, any web application contains a single virtual directory and a single Uploads folder, to/from which end users upload/download files. Here, I'm playing a little trick: though upload and download happens to/from the same folder, I'm keeping two different entry points for them. I.e., I create two different virtual directories which point to the same physical folder.

  • Create a virtual directory by name Security (your web application) in which the ASP.NET application resides.
  • Inside this folder, create a folder by name Uploads (your application subfolder, to which you upload the files). The ASP.NET application will upload files to this folder using general file upload practices.
  • Create one more virtual directory by name Downloads, and map it to the Uploads (your application subfolder, to which you upload the files) folder which is residing in the Security (your web application) folder. This virtual directory is simply meant for file downloads, and it has nothing to do with the ASP.NET application or the file upload process.

Keeping the uploads folder as it is, we are creating two entry points for the files, one is through http://localhost/security/uploads, and the other through http://localhost/downloads. Though both the virtual directories are pointing to the same folder, based on their settings, they will behave differently.


  • Unzip the attached source code on to disk.
  • Start IIS.
  • Create a new virtual directory by name Security, and map it to the source code.
  • In IIS, select the Security virtual directory (created above). You will find an Uploads folder inside it. Right click on the Uploads folder and select Properties. Remove the Read access from the Uploads folder, and provide only Write access to it.

Sample screenshot

  • Create a new virtual directory named Downloads, and map the Uploads folder (present in the Security folder) to it.
  • Open the downloads virtual directory property window, and grant only Read permissions to it, as shown below:

Sample screenshot

Using the code

Modify the following parameters in the web.config files as per your application needs:

//Application uploads folder virtual path
<add key="UploadPath" value="/Security/Uploads" />

//Entry point for downloads folder, a virtual path
<add key="DownloadURL" value="http://localhost/downloads" />

//Windows user name
<add key="BasicAuthenticationUser" value="administrator" />

//Windows user password
<add key="BasicAuthenticationPWD" value="admin$123" />

Now, let's start learning...................

What is Basic Authentication - when an unauthenticated request comes into the web server, the web server returns an HTTP 401 response, prompting the client for its credentials. The client re-requests the same resource, passing the username and password in a base-64 encoded HTTP header. (The base-64 encoding does not encrypt or protect the credentials; it merely ensures that the characters sent over the wire are in a format that won't conflict with any reserved characters.) Since the credentials are sent over the wire in plain-text, Basic Authentication should only be used when using SSL, since this ensures that the entire contents of the HTTP request are encrypted. However, in our case, we are passing the credentials to the same server through localhost, so passing credentials as clear text would not be a problem.

The .NET Framework provides the WebClient class, which is designed to simplify the HTTP request process. It contains common methods for sending data to and receiving data from a resource identified by a URI. The HttpWebRequest class is used to generate the request, and HttpWebResponse is used to retrieve the response from the server. Typically, HttpWebRequest and HttpWebResponse serve all the purposes, but in the case of Basic Authentication, an extra class comes into picture, i.e., CredentialCache.

Both the WebClient and HttpWebRequest classes make it easy to include authentication information in the request through their Credentials properties. The Credentials property accepts an object that implements ICredentials. The CredentialCache class provides a store for credentials. The intent of the CredentialCache class is to store a set of credentials for the user. When a request is made to a resource, the CredentialCache class can be interrogated and the appropriate credentials can be extracted based on the resource being requested.

The simplest use of this class involves just a few lines of code. The steps we need to perform include:

  1. Creating an instance of the class.
  2. Calling the DownloadData method, passing in the URL (which returns an array of Bytes).
  3. Writing the downloaded data's Byte using Response.BinaryWrite, which in turn prompts the user to download the file.

The following code shows how to use the CredentialCache class and the WebClient's Credentials property to make a request to a URL that is protected via Basic Authentication:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
namespace security
    /// <SUMMARY>
    /// Summary description for SecureFile.
    /// </SUMMARY>
    public class SecureFile
        public SecureFile()
            // TODO: Add constructor logic here
        public bool UploadFile(HtmlInputFile inputfile)
                string fileName = "";
                string DirPath = "";
                if(( inputfile.PostedFile != null ) && 
                   ( inputfile.PostedFile.ContentLength > 0 ))
                    fileName = System.IO.Path.GetFileName(
                                     inputfile.PostedFile.FileName );
                    inputfile.PostedFile.SaveAs( DirPath + "\\" + fileName  );
                return true;
                return false;

        public bool DownloadFile(string strFile)
                string strDownloadURL=
                string strUser=
                string strPWD=
                string strURL=strDownloadURL + "\\" + strFile;
                 //Creating an instance of a WebClient
                WebClient req=new WebClient();

                //Creating an instance of a credential cache, 
                //and passing the username and password to it
                CredentialCache mycache=new CredentialCache();
                mycache.Add(new Uri(strURL),"Basic", 
                            new NetworkCredential(strUser,strPWD));

                //Creating an instance of a Response object
                HttpResponse response = HttpContext.Current.Response;
                response.Buffer= true;

                //Keep the current page as it is, and writes 
                //the content to an new instance, 
                //which prompts the user to download the file 
                  "attachment;filename=\"" + strFile + "\"");
                byte[] data=req.DownloadData(strURL);
                return true;
            catch(Exception ex)
                if(ex.Message=="The remote server " + 
                               "returned an error: (404) Not Found.")
                    throw new Exception("File not found");
                else if(ex.Message=="The remote server" + 
                        " returned an error: (401) Unauthorized.")
                    throw new Exception("Unauthorized access");

                return false;

Enjoy!!! Any feedback would be appreciated.

Using the code

For quick implementation and demonstration purposes, I have used the administrator user, but I strongly recommend you to create a new user which has only Write permissions to the Uploads folder and no other permissions on the server/system.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Mohammed Faraz (Captain)
United States United States
I've been very passionate about writing code and building softwares since my high school time, and since then I had an opportunity to work on mission critical systems, thorough in implementing end to end retail solutions, which covers eCommerce, Order Management and Fulfillment. Currently working as Director of Advance Technology Solutions at Nisum Technologies.

You may also be interested in...


Comments and Discussions

GeneralIt will not work on big files Pin
Arash Javadi6-Mar-09 3:07
memberArash Javadi6-Mar-09 3:07 
QuestionHow will search kb article number Pin
sajan26-Mar-08 4:01
membersajan26-Mar-08 4:01 
GeneralQuestion regarding HTTP PUT Pin
Member 26337121-Mar-08 8:03
memberMember 26337121-Mar-08 8:03 
Generalfile downloading from crm3.0 Pin
vivek_5in18-Feb-08 1:03
membervivek_5in18-Feb-08 1:03 
GeneralRe: file downloading from crm3.0 Pin
Mohammed Faraz (Captain)25-Feb-08 5:47
memberMohammed Faraz (Captain)25-Feb-08 5:47 
GeneralShare located on another computer Pin
NewbieAE29-Jun-07 0:21
memberNewbieAE29-Jun-07 0:21 
GeneralNTLM Pin
andresb32124-Oct-06 6:36
memberandresb32124-Oct-06 6:36 
General2,0 . Net Conversion Please Pin
DR Delphi29-Jul-06 6:51
memberDR Delphi29-Jul-06 6:51 
Generalhi some advice please Pin
deanvanrooyen18-Apr-06 12:35
memberdeanvanrooyen18-Apr-06 12:35 
QuestionRe: hi some advice please Pin
adnanrafiq26-Aug-07 6:02
memberadnanrafiq26-Aug-07 6:02 
AnswerRe: hi some advice please Pin
cruzagr3 networks27-Nov-07 19:08
membercruzagr3 networks27-Nov-07 19:08 
GeneralI Appreciate Your Research. Pin
lonereck612-Apr-06 2:51
memberlonereck612-Apr-06 2:51 
GeneralGreat Article Pin
shabnamsyd29-Mar-06 6:45
membershabnamsyd29-Mar-06 6:45 
GeneralGreat Job and Explanation Pin
WhiteKnight19-Mar-06 13:40
memberWhiteKnight19-Mar-06 13:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.181116.1 | Last Updated 19 Mar 2006
Article Copyright 2006 by Mohammed Faraz (Captain)
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid