Reputation: 3523
I have looked across the internet with no luck, I am trying to find a suitable way to cache a username and password token on the service side so each time a connection to the service is made I don't have to create a database connection.
This is what I am trying to achieve:
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");
}
}
Is it possible to use caching when validating credentials in C# 4.0 WCF using UserNamePasswordValidator?
If so, can someone give me some clues on how to achieve this?
Upvotes: 2
Views: 852
Reputation: 1063
I would like to request the super users not to delete the answer as that could help others who wants to find the solution for their issues..!
I have implemented the the following CUSTOM security manager using key-value pair Dictionary collection for caching. Hope this helps
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");
}
}
Upvotes: 2