Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a certain URL valid only for 48 hours

Tags:

c#

asp.net

I have a need to make a certain URL valid only for 48 hours, This link is generated on the server and sent to the client via email.

What I thought of doing is embedding a encoded time stamp on the server.

  • This time stamp of course needs to be encoded, how ever I don't want my client side to have decoding capabilities.
  • Another thought is using a public encryption where the key is the user name

What are the best practices for this scenario?

like image 869
Shachaf.Gortler Avatar asked Dec 04 '25 13:12

Shachaf.Gortler


2 Answers

I would store the link in a database with an Id and an expiration date. When the user visits the link, I'll cross check the expiration date and see if it's expired.

like image 53
Dimitar Dimitrov Avatar answered Dec 07 '25 03:12

Dimitar Dimitrov


This implementation is not secure to use, see my note below.

If you'd like to implement your check like @craig1231 suggested who uses your idea to "encode" a timestamp, you can use code like this:

private const string SECRET = "secret of your choice";

private string getSHA1Hash(string strToHash)
{
    System.Security.Cryptography.SHA1CryptoServiceProvider sha1Obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
    byte[] bytesToHash = System.Text.Encoding.Default.GetBytes(strToHash);
    bytesToHash = sha1Obj.ComputeHash(bytesToHash);
    string strResult = "";
    foreach (byte b in bytesToHash)
    {
        strResult += b.ToString("x2");
    }
    return strResult.ToLower();
}

public bool IsValidRequest(long expiryTicks, string hash)
{
    var expired = new DateTime(expiryTicks);
    var toHash = expiryTicks + SECRET;
    if (expired < DateTime.Now)
        return false;
    if (hash.ToLower() == getSHA1Hash(toHash))
        return true;
    return false;
}

public string GetHashForExpiryTicks(long expiryTicks)
{
    var toHash = expiryTicks + SECRET;
    return getSHA1Hash(toHash);
}

To generate a link you can get your hash parameter like this

var hash = GetHashForExpiryTicks(DateTime.Now.AddHours(48).Ticks);

Edit 2022: Note that this is an at least suboptimal if not insecure implementation, given this a) uses SHA1 and b) does not do proper message signing. A valid implementation would sign the expiry timestamp using a proper message signing algorithm like HMAC. For an example how to sign and verify using C# and HMAC that is secure (as of 2022-01), see for example Microsoft's docs here. Note that the example signs a file and demonstartes the relevant concepts but is not as specific to the original question as my outdated above answer was.

like image 26
Georg Jung Avatar answered Dec 07 '25 02:12

Georg Jung



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!