2011-05-16 83 views
4

我有一个只有一个按钮的WPF应用程序。点击该按钮后,所有操作都会打开该服务。下面是代码:我应该在哪里阅读我的WCF服务的用户名和密码?

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) 
     { 

     } 
    } 

正如你可以看到从上面,我读从凭证节点的用户名和密码在XML文件以验证客户端。难道是正确的已经在这里的位置,因为我本来就在我的验证方法定义:

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"); 
    } 

但上述问题是,无论我进入c.ClientCredentials.UserName.UserName和c。 ClientCredentials.UserName.Password在达到Validate方法时被覆盖。举例来说,在我的按钮点击,如果我只是有:

c.ClientCredentials.UserName.UserName = "test1";
c.ClientCredentials.UserName.Password = "test1";

上述失败,但是当它进入验证方法,其中,我读了具有用户名和密码的XML文件属性作为测试和测试,它会通过。

作为一个方面说明,我注意到我的Validate方法被调用,但我似乎无法进入。调试器符号不会被加载。

+3

为什么要那样做你自己的安全,而不是依赖于WCF的内置安全功能的参数? – 2011-05-16 15:38:15

+0

你能澄清吗?我正在使用覆盖UserNamePasswordValidator的Validate方法。这不是怎么做到的?我所做的只是从xml文件中读取用户名和密码。 – Xaisoft 2011-05-16 15:40:15

+3

否 - 执行此操作的方法是使用Windows凭据(在LAN /企业环境中)或使用例如ASP.NET会员系统。让WCF执行所有检查和所有事情 - 您只需设置要查找有效用户和密码的位置即可。 – 2011-05-16 15:54:46

回答

1

要覆盖你的阅读

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; 
相关问题