我没有运气浏览互联网,我试图找到一种合适的方法来缓存服务端的用户名和密码令牌,所以每次连接到服务时我都不必创建数据库连接。
这就是我想要实现的目标:
public class ServiceAuth : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
var user = Repository.Authenticate(userName, password);
if (user != null)
{
// Perform some secure caching
}
else
throw new FaultException("Login Failed");
}
}
使用UserNamePasswordValidator在C#4.0 WCF中验证凭据时是否可以使用缓存?
如果是这样,有人可以给我一些关于如何实现这一目标的线索吗?
答案 0 :(得分:2)
我想请求超级用户不要删除答案,因为这可以帮助其他想要找到问题解决方案的人。!
我使用键值对Dictionary集合实现了以下CUSTOM安全管理器以进行缓存。希望这有帮助
public class SecurityManager : UserNamePasswordValidator
{
//cacheCredentials stores username and password
static Dictionary<string, string> cacheCredentials = new Dictionary<string, string>();
//cacheTimes stores username and time that username added to dictionary.
static Dictionary<string, DateTime> cacheTimes = new Dictionary<string, DateTime>();
public override void Validate(string userName, string password)
{
if (userName == null || password == null)
{
throw new ArgumentNullException();
}
if (cacheCredentials.ContainsKey(userName))
{
if ((cacheCredentials[userName] == password) && ((DateTime.Now - cacheTimes[userName]) < TimeSpan.FromSeconds(30)))// && timespan < 30 sec - TODO
return;
else
cacheCredentials.Clear();
}
if (Membership.ValidateUser(userName, password))
{
//cache usename(key) and password(value)
cacheCredentials.Add(userName, password);
//cache username(key), time that username added to dictionary
cacheTimes.Add(userName, DateTime.Now);
return;
}
throw new FaultException("Authentication failed for the user");
}
}