如何生成一个独特的令牌,该令牌24小时后过期? [英] how to generate a unique token which expires after 24 hours?
问题描述
我有一个WCF web服务,如果用户是有效的,它检查。
如果该用户是有效我要生成哪些24小时后期满的令牌。
公共BOOL authenticateUserManual(用户名字符串,字符串密码,串语言,字符串标记)
{
如果(Membership.ValidateUser(用户名,密码))
{
//////////
字符串标记= ????
////////// 返回true;
}
其他
{
返回false;
}
}
有两种可能的方法;要么你创造独特的价值,并与创建时间以及一些地方保存,例如在数据库中,或者你把创建时间令牌里面,这样以后可以去code,看看它创建时间。
要创造一个独特的标记:
字符串标记= Convert.ToBase64String(Guid.NewGuid()ToByteArray());
创建包含时间戳的唯一令牌的基本例如:
字节[] =时间BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
字节[]键= Guid.NewGuid()ToByteArray()。
字符串标记= Convert.ToBase64String(time.Concat(密钥).ToArray());
要取消code令牌来获取创建时间:
字节[]数据= Convert.FromBase64String(令牌);
当日期时间= DateTime.FromBinary(BitConverter.ToInt64(数据,0));
如果(当< DateTime.UtcNow.AddHours(-24)){
// 太老
}
请注意:如果需要使用时间戳令牌是安全的,你需要对它进行加密。否则,用户可以找出它所包含的内容,并创建一个虚假的令牌。
I have a WCF Webservice which checks if the user is valid.
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.
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.
这篇关于如何生成一个独特的令牌,该令牌24小时后过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!