我浏览过互联网,但没有运气,我正在尝试找到一种合适的方法来在服务端缓存用户名和密码 token ,这样每次与服务建立连接时,我就不必创建一个数据库连接。
这就是我想要实现的目标:
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 中的凭据时是否可以使用缓存?
如果是这样,有人可以给我一些关于如何实现这一目标的线索吗?
最佳答案
我想请求 super 用户不要删除答案,因为这可以帮助其他想要找到问题解决方案的人..!
我已经使用键值对字典集合实现了以下自定义安全管理器进行缓存。希望这有帮助
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");
}
}
关于c# - WCF 用户名密码验证器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960487/