Where should I read my username and password for my WCF Service?
I have a WPF application that has just one button. When the button is clicked, all it does is open the service. Here is the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.TestServiceClient c = new ServiceReference1.TestServiceClient();
XDocument doc = XDocument.Load(@"c:\Test\Test.xml");
c.ClientCredentials.UserName.UserName = doc.Root.Element("Credentials").Attribute("username").Value;
c.ClientCredentials.UserName.Password = doc.Root.Element("Credentials").Attribute("password").Value;
try
{
c.Open();
}
catch (Exception ex)
{
}
}
As you can see from above, I am reading the username and password from a Credentials node in an xml file to validate the client. Is it proper to have it located here, because originally, I had it defined in my Validate method:
public override void Validate(string userName, string password)
{
// XDocument doc = XDocument.Load(@"c:\Test\Test.xml");
// userName = doc.Root.Element("Credentials").Attribute("username").Value;
// password = doc.Root.Element("Credentials").Attribute("password").Value;
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException("password");
// check if the user is not test
if (userName != "test" || password != "test")
throw new FaultException("Username and Password Failed");
}
But the problem with the above is that whatever I pass into c.ClientCredentials.UserName.UserName and c.ClientCredentials.UserName.Password gets overriden when it reaches the Validate method. For example, in my button click, if I just have:
c.ClientCredentials.UserName.UserName = "test1";
c.ClientCredentials.UserName.Password = "test1";
The above should fail, but when it goes into the Validate method where I read the xml file that has the username and password a开发者_开发问答ttribute as test and test, it will pass.
As a side note, I noticed that my Validate method gets called, but I can't seem to step into. The debugger symbols don't get loaded.
you are overwriting the parameter with your read
public override void Validate(string suppliedUserName, string suppliedPassword){
// ...
string validUserName = doc.Root.Element("Credentials").Attribute("username").Value;
string validPassword = doc.Root.Element("Credentials").Attribute("password").Value;
精彩评论