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
Resources: