How to Generate a Unique Token Which Expires After 24 Hours

how to generate a unique token which expires after 24 hours?

There are two possible approaches; either you create a unique value and store somewhere along with the creation time, for example in a database, or you put the creation time inside the token so that you can decode it later and see when it was created.

To create a unique token:

string token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] data = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
if (when < DateTime.UtcNow.AddHours(-24)) {
// too old
}

Note: If you need the token with the time stamp to be secure, you need to encrypt it. Otherwise a user could figure out what it contains and create a false token.

C# How to generate token by code which will be valid for next 5 minutes

This may not be the kind of implementation you're looking for, but take a look at
this answer.

Excerpt:

Basic example of creating a unique token containing a time stamp:

byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
string token = Convert.ToBase64String(time.Concat(key).ToArray());

To decode the token to get the creation time:

byte[] tokenByteArray = Convert.FromBase64String(token);
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(tokenByteArray, 0));
if (when < DateTime.UtcNow.AddMinutes(-5)) {
// too old
}

(I changed the decode section to match your requirement for a 5 minute token invalidation, and changed the original "data" variable to "tokenByteArray" for clarity.)



Clarifications in response to comment request

Drilling down into why we use BitConverter.ToInt64(tokenByteArray, 0):

This whole implementation relies on that final deserialization operation which allows us to rebuild a copy of the original DateTime object that we started with.

This rebuilding / deserialization is accomplished by calling the static DateTime.FromBinary() method, which takes a 64-bit signed integer (or long data type) as its parameter.

Since we originally converted our DateTime object down into a byte[], we need to deserialize the string token that we generated to extract our DateTime value. And seeing that DateTime.FromBinary() requires a 64-bit signed integer parameter, we need to convert our string token's byte[] by calling BitConverter.ToInt64(tokenByteArray, 0) - (the 0 just denotes where in the array to start converting).

Now we just feed the converted 64-bit integer into the DateTime.FromBinary() method, and we're done.

Example / Fiddle

  • My .NET Fiddle

Resources:

  • BitConverter.ToInt64() - Documentation
  • DateTime.FromBinary() - Documentation

How do i make a token expire

You can do this way

create a table called password_recovery with the following fields

  • id Primary Key auto incremented
  • iduser int(11) // length you may choose as per your requirement
  • token_key varchar(100) // length you may choose as per your requirement
  • expire_date datetime
  • created_date datetime

Now while someone request for password recovery usually by entering login name or email get the iduser for that user. Then generate a token.
You can set the expire_date as you want. Lets say its 1 day from now, you can use strtotime() to generate that. Insert these values in the password_recovery table.

Then send the email to the users email id something like

yourdomain.com/passrecover.php?h=[token from above]

Once user clicks on the link, run a code to check if the token is valid and if not expired . If so display the password reset form. You will have the iduser from that token. Else display the error message.

Finally once user reset the password , delete the row from the table.

You can in addition have a cronjob script to delete the expired tokens from the table.

How do i make a token expire time

Best practice is to have a database table that stores the information of tokens created...

id | expiry_timestamp | token ...

Then edit the code to store each token created with its expiry_timestamp...

function token($length = 40, $expiry) {
// Set expiry_timestamp..
$expiry_timestamp = time() + $expiry;

// Generate the token...
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$token = 12000;
$token = srand(floor(time() / $token));
for ($i = 0; $i < $length; $i++) {
$token .= $characters[rand(0, $charactersLength - 1)];
}

/** Do a quick manipulation in the token table...
* ...Connect to database table then execute following SQL statement..
* mysqli_query($link, "INSERT INTO token_table (token, expiry_timestamp) VALUES($token, $expiry_timestamp)");
*/

return array($token,$expiry);
}

Just incase you want to check if it has expired, you can use another function to fetch its expiry_timestamp and confirm whether or not, it is greater than the current timestamp

Any way i can create access token manually (without identity server 4 or similar stuff) in .net

able to do it using RSASecurity Details are mentioned in my other post How to create RsaSecurityKey from Public/Private Key Pair

how to making token after 30 minutes with php

You can store token in cookie which expire after 30 minutes. You can check if cookie has value then take it from cookie otherwise create new token.

<?php
function token($length=6){
$cookie_name = "token_set";
if(isset($_COOKIE[$cookie_name]) && $_COOKIE[$cookie_name] != "") {
$randomstring = $_COOKIE[$cookie_name];
}
else
{
$character = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomstring = "";
$num_valid_chars = strlen($character);
for ($i = 0; $i < $length; $i++)
{
$random_pick = mt_rand(1, $num_valid_chars);
$random_char = $character[$random_pick-1];
$randomstring .= $random_char;
}

setcookie($cookie_name, $randomstring, time() + (1800), '/'); //set for 30 mins
}

return $randomstring;
}


Related Topics



Leave a reply



Submit