September 28th, 2012, 08:25 AM
WCF Custom User Name Password Validator to read from Database
I am using a Custom User Name Password Validator in my WCF Service. It works if I hard code the username and password in the validator function, but , I am trying to have my WCF service to validate username and password against those stored in my database, and that part does not work.
Can some one please let me know if I am supposed to do something else to make it validate against credentials stored in the DB. I have tested the entire database connection and reader related code in the client application and it works. It does not work when I use it in the WCF service.
Thank you for your help.
Here is my code:
class CustomUserNamePassValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
public override void Validate(string userName, string password)
string MyUser = "";
string MyPass = "";
string connectionString = "Initial Catalog=MyDB;Data Source=MyServer;Integrated Security=SSPI";
SqlConnection MyConnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("Exec MyDB.dbo.GetCredentials", MyConnection);
SqlDataReader MyReader = command.ExecuteReader();
MyUser = MyReader["UserName"].ToString();
MyPass = MyReader["Passwrd"].ToString();
catch (Exception exp)
MyFaultException theFault = new MyFaultException();
theFault.Reason = "Database Connection Error: " + exp.Message.ToString();
throw new FaultException<MyFaultException>(theFault);
if (userName == null || password == null)
throw new SecurityTokenException("security Error: No Credentials Passed");
if (userName != MyUser && password != MyPass)
throw new SecurityTokenException("security Error: Wrong Credentials Passed");
//It works if I do it this way
//if (!(userName == "MyUser" && password == "MyPass"))
// throw new SecurityTokenException("security Error: Wrong Credentials Passed");
Tags for this Thread
Click Here to Expand Forum to Full Width
This a Codeguru.com survey!