Asp. NET implementation of File Protection download Basic Article _ Practical Skills

Source: Internet
Author: User
Tags anonymous httpcontext zip extension password protection
Requirements for document protection downloads

If we need to sell digital forms of goods on the site, such as electronic books, digital oil painting, and so on, how to prevent unauthorized users from illegally downloading your product while it is available for authorized users to download normally? Through forms authentication, this problem can only be partially resolved. In this article, I'll explain how to prevent some users from accessing certain files on the site, even if they can be browsed directly by those users.

There are many ways to solve this problem, but some of the methods themselves are problematic. In this article, we will examine some of the technologies commonly used by software vendors and then introduce a new solution. Note that this is an introduction to the ASP.net site.

  Ii. Common File Protection techniques

Many of us have experience with buying software online, so we may have experienced the usual protections for file downloads. Below, we examine them.

Compressed file password protection

This method of protection is relatively simple, not to prevent you from downloading files, but to prevent unauthorized people from extracting the contents of files from compressed files, because WinZip and many other compression programs provide password protection. However, the disadvantage of this approach is also obvious, if you allow someone to access the contents of the file, you must provide him with a password, then you can not prevent this person to pass the password to others. In fact, if you search the Internet, you'll find all sorts of passwords everywhere. When this protection is used, only the authorized user is expected to be a moral person and will not pass the password. Alternatively, this protection is provided at a level that compresses the file for each life into a different password and then passes it on to him. Of course, this requires a file storage solution because you need to be able to control the files that are sent to the user. This leads to the second method of file protection.

Email

Many software vendors do not post files to their Web sites, but send an email to the user who buys the software, telling them to download the details, or sending them directly along with the file. An e-mail message can contain a file download link and limit the valid time for that link. Sometimes, software vendors can combine this technology with password protection. Once the file is in the hands of the user, the rest of the protection depends on the software license and registration. Other e-mail based solutions also have dynamically generated file name methods.

Temporary file name

Some software vendors will use GUIDs or other secret naming techniques to generate a file name that is hard to guess, while also enabling files to be downloaded only within a specified time.

  Third, technical analysis

Although these technologies are still in use, they are not able to open up a customer area on your site, allowing users to check their purchase history and download their software at any time. In my opinion, sites that provide similar functionality can provide a better user experience and are easier to manage for software vendors-after a user buys a product, you only need to send a link to the user that contains the license key and their corresponding customer area on the site. In this way, users know that they can log in and download the software at any time, they will be more comfortable, even if lost software files are not afraid.

To this end, we will introduce a asp.net forms authentication and a protection scheme called HTTP handlers to provide this good user experience. The class System.Web.UI.Page itself is an HTTP handler and is registered in the Web.config file of your machine.

Content navigation

  Four, HTTP processing program

In fact, using ASP.net to customize HTTP handlers is not as complex as people think, and we'll discuss this topic in a way that is as easy to understand as possible. There are many applications for HTTP handlers, but we are here to discuss their application in file protection issues.

Figure 1 Extension Mappings in IIS

Here we will describe what a handler is and how it works, and we strive to do it as easily as possible. When you request an ASPX page in a asp.net environment, IIS passes the request to the appropriate DLL for processing. The so-called HTTP handlers are those classes that handle the requests that IIS passes to them. When you install ASP.net on a machine, you add a list of table entries to IIS (see Figure 1). These table entries contain the extensions (ASPX, ASMX, and so on) of the files that you want asp.net to process. When we request an ASPX, when IIS receives the request, it passes it to the appropriate DLL, in this case aspnet_isapi.dll, which then produces the corresponding HTTP handler instance to process the request. In the ASPX page, the HTTP handler used is a page class in the System.Web.UI namespace.

In the case of ASPX pages, page handlers are used to control and trigger lifecycle events, and when you browse an ASPX page, almost everything is handled by it. However, you can write a custom HTTP handler to intercept all requests made by the browser to adjust or customize the actions that normally occur. To do this, we need a variety of techniques, and I'll start with the IIS table entries in this article, as well as forms authentication related content.

  V. IIS and Forms authentication

As mentioned earlier, IIS sends the registered extension to aspnet_isapi.dll. Figure 1 shows the registered extensions that were found. We can see this dialog box in the virtual directory or the "Configuration" option in the "Properties" of the website. Any files with registered extensions that are processed by Aspnet_isapi.dll are subject to ASP.net forms authentication. Here's a brief introduction to the mechanism of forms authentication.

The custom HTTP handler is actually the class that implements the IHttpHandler interface. Forms authentication allows you to prevent anonymous users from accessing certain Web pages without authorization. File Web.config uses the following code to set forms authentication:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

<AuthenticationMode= "Forms">
<FormsLoginurl= "Login.aspx"/>
</Authentication>
<Authorization>
<DenyUsers="?"/>
</Authorization>

The above code prevents all pages from being accessed by unauthenticated users. If an anonymous user attempts to access a Web page, the code automatically redirects them to the Login.aspx page. As a result, site developers can decide which authentication method to use on this page, but in ASP.net 2.0, developers can easily use new security controls to do this work.

Now, we said that this code can prevent unauthenticated users from accessing any page, but it is accurate to prevent unauthorized users from accessing all the files that were intercepted by Aspnet_isapi.dll. This will be explained in detail later. To pave the back of this article, we need to first describe some of the specifics of the sample E-commerce site.

Content navigation

  Vi. planning of protection measures

Suppose our site allows users to buy software online, but before purchasing or downloading software, users must register first. Then, create a table for users and products, and then store the user name and product serial number separately. When a user buys the software, it associates users and products by creating a record in another table. We call this table userproducts.

We want to store all the software product files in a folder called files, which is located in the root folder of the Web site. The Product table has a field for the product file name that corresponds to a compressed file in the Files folder. We call this field productfilename. Here's a step-by-step description of how to protect these zip files.

  Seven, protect all the compressed files

First, we want to prevent all compressed files from being downloaded by unauthenticated users. We want all files with the. zip extension to be processed by ASP.net forms authentication so that anonymous users cannot access them. Although this step is not the most critical, it does provide security for the file.

Typically, if you can browse directly to a zip file on a Web site, the site prompts you to open or save the file to your hard disk. We want asp.net to intercept a request for a file with the extension zip, so you need to add the appropriate extension in the IIS Application mapping table.

To do this, you can open the management console for IIS, locate the appropriate site or virtual directory, right-click and select the Properties option, and you will see figure 2. If you click the Configuration button on the Web Site or Virtual Directory tab, you will see the extension tables and the DLLs that are used to process them, as shown in Figure 1. We have to add the extension "zip" to this list, so you can click the "Add" button and then type "zip" in the extension text box, and click the Limit to Verb option button.

Figure 2 Web Site Properties

Figure 3 Navigating to Aspnet_isapi.dll

Content navigation

In the verbs text box, type, POST, and DEBUG to indicate that the aspnet_isapi.dll intercepts a request for a zip type file. In the executable: text box, navigate to the location of the Aspnet_isapi.dll file, as shown in Figure 3. This file is located in the C:\WINDOWS\Microsoft.NET\Framework\ directory under the appropriate Framework version folder, as shown in Figure 4.

  

Figure 4 Adding a zip extension mapping to IIS

  

Figure 5 Mapping the zip extension

After the table entry is established, our mapping table will be shown in Figure 5. Note that all other extensions in this table, such as vbproj, Config, and so on, Aspnet_isapi.dll also block these extensions for protection. This is why you are redirected to a reject page when attempting to browse the Web.config file.

After you create this table entry in IIS, if you try to browse directly to the zip file on our site, IIS redirects it to the login page if the user is not authenticated. So now we have been able to prevent anonymous users from downloading our files, but once the site is authenticated, this protection is not in use.

Content navigation

  Viii. more specific measures of protection

Our goal is to allow authorized users to browse a page that contains the software they have purchased, and to download a specific item by clicking on the link. When you list products, you can use the table structure, but how do you protect the links? The approach we introduced earlier was to prevent anonymous users from downloading compressed files, but now we want to prevent authorized users from browsing the compressed files directly. To do this, we need to write a custom handler.

A custom HTTP handler is a class that implements the IHttpHandler interface. This interface defines a method called ProcessRequest, and a Boolean-type property named IsReusable. This property determines whether other requests can take advantage of the same handler, so it simply returns a truth value. This method will receive an argument of the HttpContext type. This variable gives us the right to access the entire context of the request, including the information in the request and the method of ordering the request in another direction.

Now, we're going to create a handler called Filedenialhandler, which is to stop a request and redirect the user to a page to notify them that access is denied. When this handler obtains the request, the ProcessRequest method is invoked and the redirection is performed.



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

Public voidProcessRequest (HttpContext context)
{
Context. Response.Redirect (
"~/downloads/files/accessdenied.aspx");
}

As you can see, this page is located in the Downloads/files folder in the root directory, and the complete FileDenialHandler.cs handler looks like this:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

UsingSystem;
UsingSystem.Data;
UsingSystem.Configuration;
Usingsystem.web;
UsingSystem.Web.Security;
UsingSystem.Web.UI;
NamespaceDotNetDude.Web.UI
{
Public ClassFiledenialhandler:ihttphandler
{
Public voidProcessRequest (HttpContext context)
{
Context. Response.Redirect (
"~/downloads/files/accessdenied.aspx");
}

Public boolIsReusable
{
Get
{
Return True;
}
}
}
}

Now, this Filedenialhandler class has done nothing, so it must be written to the site. To do so, we put it in the Web.config file .

File Web.config lists all the special handlers for the configuration section and provides them with the appropriate information, including the predicate that instantiates the handler, the wildcard path to the file to be processed by the handler, and the type definition for the custom handler. In this example, the added configuration section looks like this:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

<httphandlers>
<AddVerb="*"Path= "*.zip"
Type= "DotNetDude.Web.UI."
Fileprotectionhandler,
Dotnetdude.httphandlers "/>
</httphandlers>

The parameter type is standard. NET fully qualified name, and a component assembly name is combined with a comma. You can omit an assembly name when you write a handler in an actual Web project.

Now this entry forwards all the compressed file requests to the new handler, so immediately redirects the request to the Access Denied page. Even if you skip the IIS entry in this example, it will still work as usual as these things are left to our handlers. However, the effect we want is to get the system to navigate to the login page first before an anonymous user is judged to have access to an illegal zip file.

If you examine the Web.config file in the framework directory, you will find a list of handlers that handle the common file name extension for asp.net. The handlers that define the portions of this file determine how IIS properly forwards the ASPX page, the ASMX Web service, and all other files. This handler list also defines which file name extensions are disabled, such as *.config. In fact, you can use a handler called HttpForbiddenHandler to disable all files ending with the extension. config and automatically display an "HTTP 403error forbidden:access is denied" page.

So you might ask, is there nothing more than a Microsoft-supplied handler to handle compressed files? The answer is, of course, but we need our own "Access denied" page so that we can customize our own rejection page to be consistent with our website style. In some cases, we also want to provide users with more information and even send an "unauthorized attempt" class email to the administrator.

This is just to prevent all compressed files from being downloaded, but what do we actually want to do? By the way, we're going to get absolute control of how we download files from our site. We do not want users to browse directly to the compressed file. With the table structure, we can create a project, a list of users, and a relational table for each user to buy a product. So if we have a username and a product serial number, we can use a simple database query to determine whether the user purchased the product. At the same time, we also want users to click a link to start the query and determine whether the file is allowed to download. These features are indeed very desirable.

Content navigation

  Nine, control download

Next, we start with how to write a handler for some file requests, and how to install the handler. The function of our handler is simple, it simply redirects the request to another place. Asp. NET also provides another file name extension, ashx, which does not need to be installed into the Web.config file. We can create a class that ends with this extension to implement the IHttpHandler interface and navigate directly to the class. It's actually very similar to a page, except that it doesn't use Web Forms and Code-behind classes, so it's a much simpler solution.

Now we create a new handler called DOWNLOAD.ASHX, and let the user browse to the location of the handler and specify some information in the QueryString parameter. The following URL is the download link:

~/downloads/download.ashx? Product=101

This URL represents the download of the file associated with Product 101. A user or link can access the URL above to attempt to download a file, at which point the handler's ProcessRequest method executes.

Authenticate the user with standard forms authentication, which allows access to the users object in our site context. Keep in mind that the HTTP context is passed to the ProcessRequest method of the handler, so you can access the content you want. Object user allows us to obtain the name of an authorized user using User.Identity.Name, and we can also use this method to access users in the user table. To access the user's name, we use the User.Identity.IsAuthenticated value to check whether they have been authenticated, and if not, redirect it to access denied. In addition, we will access the requested product number, as shown in the following code:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

Context. request.querystring["Product"]

In this way, we get the product number and user name. With both, we can access the Userproducts table and determine if the user has purchased the product. In addition, this table also stores the file name of the product.

Now that you have the user name and product number, you are determined to use them in addition to the user purchase. If the user does not purchase the appropriate product, we redirect it to the previous handler and return to an Access Denied page. For brevity, we redirect it to a page that tells them that they have not purchased the product and tells them how to make the purchase.

If you are sure that the user purchased the product, you can use the Productfilename field to find out which files the user can view. Here, we don't store the full path, just store the filename. If necessary, we can get the folder from the settings in Web.config, so we finally get the full file path and name and authorize the download. Here we do this by calling the Startdownload method:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

Private voidStartdownload (
HttpContext context,StringDownloadFile)
{
Context. Response.Buffer= True;
Context. Response.Clear ();
Context. Response.AddHeader (
"Content-disposition",
"attachment; Filename=" +DownloadFile);
Context. Response.ContentType=
"Application/zip";
Context. Response.WriteFile (
"~/downloads/files/" +DownloadFile);
}

The ProcessRequest method here calls the Startdownload method, and the complete DOWNLOAD.ASHX code looks like this:



Code highlighting produced by Actipro Codehighlighter (freeware)
http://www.CodeHighlighter.com/

<%@ WebHandler Language="C#"Class="Download" %>
UsingSystem;
Usingsystem.web;
Public ClassDownload:ihttphandler
{
Public voidProcessRequest (HttpContext context)
{
If(Context. User.Identity.IsAuthenticated)
{
If(Context. request.querystring["Product"]!= Null
&&Context. request.querystring["Product"]!= "")
{
IntProductID=Convert.ToInt16 (
Context. request.querystring["Product"]);
StringUserName=Context. User.Identity.Name;
Userproduct Product=Userproductfactory.getproductbyuser (
UserName, ProductID);
If(Product!= Null)
Startdownload (product. FileName);
Else
Context. Response.Redirect (
"~/downloads/files/accessdenied.aspx");
}
}
}

Public boolIsReusable
{
Get
{
Return False;
}
}
Private voidStartdownload (StringDownloadFile)
{
Context. Response.Buffer= True;
Context. Response.Clear ();
Context. Response.AddHeader (
"Content-disposition",
"attachment; Filename=" +DownloadFile);
Context. Response.ContentType= " application/zip " ;
      context. Response.WriteFile (
         ~/downloads/files/) + downloadFile);
  }
}

This method receives the name of the file as well as the HttpContext. From here, we will empty the response buffer, set a new header, and then set the content type. Finally, the file is printed using the WriteFile method, and the end user receives a file to save or open the window.

Note that using WriteFile to output a zip file, instead of Response.Redirect, redirects the user to the Access denied page. With this technology, smart users can navigate to download.ashx files by bypassing security checks. But even if they try to navigate directly to the zip file, they are redirected to the access Denied page by the Filedenialhandler handler.

Note the differences between the two types of handlers. One is the standard C # (or vb.net) class that can be placed in an external component, which is ideal if you need to write reusable handlers, because you can compile them into a dynamic link library and share them among different sites. Of course, we need to register them in the Web.config file. For ashx type handlers, you can add them to your site like an ASPX page. In fact, we can use other techniques to accomplish similar download.ashx functions, but ashx handlers are a much simpler solution. Using HTTP handlers is one of the most important methods for

10, summary

Using asp.net to protect file downloads. By combining with other technologies, we can not only prevent unauthorized users from downloading files, but also gain absolute control over how users download files, and hope this article will help you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.