Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a protected link

Tags:

c#

.net

Is there a way to create a protected download link which is random, expiry, requires a password and pointing to a specific file in C# that is associated with IIS 7.0?

Several random links can link to the same file.

Built-in codes or perhaps 3rd party libraries?

For example, http://www.example.com/<some random gibberish>/<md5 of file>/file.jpg

like image 654
user303907 Avatar asked May 24 '26 00:05

user303907


1 Answers

One way to do this would be to use GUIDs. GUIDs are designed not to collide, and that design also leads to a difficulty in guessing valid GUIDs. I'm sure someone out there will tell me that this is not very secure! Well, you are also protecting with a password. It is pretty easy to generate a GUID in C#.

I guess what you need is firstly a way of ingesting the files that you want to protect in this way, and secondly a handler that will respond to requests in a given path and inspect the GUID in the path to determine if it's valid.

You'd then need a database back end to maintain lists of GUIDs corresponding to URLs, the password (preferably crypted) and the expiry date. The handler would inspect the entry for the requested URL/GUID to see if the link has expired, then prompt the user (could do this via a web form easily enough) for the password and check this against the crypted password stored in the database.

To generate a GUID, you want:

System.Guid.NewGuid().ToString()

To create a module that is called before every request (for IIS7) you can add an entry to your web.config like so:

<modules>
  <add name="MyDownloadModule" type="Example.MyDownloadModule, Example"/>
</modules>

where MyDownloadModule is the class containing your handler, in the namespace Example.

Inside that class you then need to implement the IHttpModule interface, in particular overriding the methods:

public string ModuleName { 
    get { return "MyDownloadModule"; }
}

public void Init(HttpApplication app) {
    // Add an event handle which is called at the beginning of each request
    app.BeginRequest += new EventHandler(this.AppBeginRequest);
}

//
// Our event handler for the BeginRequest event
//
private void AppBeginRequest(Object source, EventArgs e)
{
    HttpRequest request = app.Context.Request;

    //
    // Is this a file download?
    //
    if (request.AppRelativeCurrentExecutionFilePath == "~/downloads") // or whatever
    {
          // this is where you work your GUID inspecting magic
    }
}

Going about it this way means this will be called for every request to the server, which may not be what you want.

like image 121
Mike Pollitt Avatar answered May 26 '26 14:05

Mike Pollitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!