C# WCF UserNamePasswordValidator缓存
我在互联网上浏览过,但运气不好,我正试图找到一种合适的方式在服务端缓存用户名和密码令牌,这样每次连接到服务时,我就不必创建数据库连接 这就是我努力实现的目标:C# WCF UserNamePasswordValidator缓存,c#,wcf,authentication,.net-4.0,C#,Wcf,Authentication,.net 4.0,我在互联网上浏览过,但运气不好,我正试图找到一种合适的方式在服务端缓存用户名和密码令牌,这样每次连接到服务时,我就不必创建数据库连接 这就是我努力实现的目标: public class ServiceAuth : UserNamePasswordValidator { public override void Validate(string userName, string password) { var user = Repository.Authenticat
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中的凭据时,是否可以使用缓存
如果是这样的话,有人能给我一些关于如何实现这一点的线索吗?我想请求超级用户不要删除答案,因为这可能会帮助其他希望找到问题解决方案的人 我已经使用键值对字典集合实现了以下自定义安全管理器,用于缓存。希望这有帮助
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");
}
}
公共类安全管理器:UserNamePasswordValidator
{
//cacheCredentials存储用户名和密码
静态字典缓存凭据=新建字典();
//cacheTimes存储用户名和用户名添加到字典的时间。
静态字典cacheTimes=新字典();
公共覆盖无效验证(字符串用户名、字符串密码)
{
如果(用户名==null | |密码==null)
{
抛出新ArgumentNullException();
}
if(cacheCredentials.ContainsKey(用户名))
{
如果((cacheCredentials[userName]==password)和((DateTime.Now-cacheTimes[userName])
如果用户名/密码组合不再有效(即不再在数据库中),会发生什么情况?缓存方法如何处理这种情况?web服务是无状态的。您打算如何识别您的个人客户?在这种情况下,缓存似乎是个坏主意。我希望web服务为登录方法发出一次身份验证令牌,然后在后续调用中验证此身份验证令牌。因此,客户端将存储令牌并在后续调用中重用它。以类似于ASP.NET中的表单认证工作的类似方式,@伯纳德这不是我现在需要考虑的问题。我只是想证明这是否可行,然后看看赞成者和反对者afterwards@AndyClark:这是绝对可能的,我只是不确定这是否是一种明智的方法。@andycark:您可以创建一个singleton类来缓存从数据库检索到的所有用户名/密码组合。如果用户名在缓存中,请从缓存中检索相应的密码,否则请转到数据库,检索用户名/密码,然后将其存储在缓存中。我支持您的动议:我想请求超级用户也不要删除答案。。仅仅因为有些人可能因为他们的情景范例而看不到做某事的理由,并不意味着有些人对你这样的答案没有一个有用的目的,这在目前可能足以满足我的目的。不是每个人都在网络上工作,也不是每个人都有一个连接到互联网的系统。