c# - WCF 用户名密码验证器缓存

标签 c# wcf authentication .net-4.0

我浏览过互联网,但没有运气,我正在尝试找到一种合适的方法来在服务端缓存用户名和密码 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/

相关文章:

c# - 从外部域 (AWS S3) 加载图像并将其存储在浏览器内存中

wcf - 如何从 .NET 客户端应用程序进入 WCF Rest 服务?

php - https登录后续页面应该使用http吗?

java - 登录网站 (Java)

c# - 字符串未被识别为有效的日期时间

c# - 如何在我的 Web 服务 POST 方法中反序列化 JSON

c# - IssuedTokenAuthentication AudienceUriMode =“从不”

jsp - java客户端证书认证

c# - 使用表达式构建器进行选择的动态 lambda

C# WCF 多客户端