2

我浏览了互联网,但没有运气,我试图找到一种合适的方法在服务端缓存用户名和密码令牌,因此每次连接到服务时,我都不必创建数据库连接。

这就是我想要实现的目标:

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 中验证凭据时是否可以使用缓存?

如果是这样,有人可以给我一些关于如何实现这一目标的线索吗?

4

1 回答 1

2

我想要求超级用户不要删除答案,因为这可以帮助其他想要找到解决问题的人..!

我已经使用键值对字典集合进行缓存实现了以下 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");       
    }
}
于 2013-02-05T17:26:40.800 回答