如何生成一个在 24 小时后过期的唯一令牌? [英] how to generate a unique token which expires after 24 hours?
问题描述
我有一个 WCF Web 服务,用于检查用户是否有效.
I have a WCF Webservice which checks if the user is valid.
如果用户有效,我想生成一个 24 小时后过期的令牌.
If the user is valid I want to generate a token which expires after 24 hours.
public bool authenticateUserManual(string userName, string password,string language,string token)
{
if (Membership.ValidateUser(userName,password))
{
//////////
string token = ????
//////////
return true;
}
else
{
return false;
}
}
推荐答案
有两种可能的方法;您可以创建一个唯一值并与创建时间一起存储在某个位置,例如在数据库中,或者将创建时间放在令牌中,以便稍后对其进行解码并查看它的创建时间.
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.
要创建唯一令牌:
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.
这篇关于如何生成一个在 24 小时后过期的唯一令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!