代码之家  ›  专栏  ›  技术社区  ›  to StackOverflow

如何在WCF客户端配置文件中指定Windows凭据

  •  25
  • to StackOverflow  · 技术社区  · 15 年前

    我有一个使用basichttpbinding和Windows身份验证的wcf服务。 大多数客户端都是域帐户,并使用其默认凭据连接到服务。

    现在,我想从运行在本地帐户下的ASP.NET客户端连接到该服务。我想使用ASP.NET应用程序可用的Windows凭据(域\用户和密码)连接到WCF服务。

    我知道我可以使用clientBase<t>.clientCredentials在代码中执行此操作。

    有没有方法在客户端的web.config文件中指定凭据(域\用户和密码),这样我就不必更改代码了?

    编辑

    如果无法在配置文件中完成,是否有方法使用System.net.icredentials或System.net.NetworkCredential作为WCF服务的凭据?

    .NET框架提供这些作为提供网络凭据的同种方式,但对于WCF,这似乎是为了支持基于不相关System.ServiceModel.Description.ClientCredentials类的新的不兼容系统而放弃的。

    编辑2

    接受Marc对原始问题的回答-在客户机配置文件中似乎没有办法做到这一点:(

    我认为这是WCF中的一个缺陷——我不接受微软故意阻止我们将凭证放入配置文件——毕竟它们必须存储在某个地方,而且框架还包括加密配置文件的功能。我想我可以为此创建一个定制的行为拉伸元素,但它应该是现成的。

    还有一点不一致:system.net/mailsettings/smtp/network配置元素允许指定凭据,那么为什么不指定wcf呢?

    关于使用System.net.NetworkCredential的第二个问题,它似乎来自 this blog 至少在使用Windows身份验证时,可以使用以下代码:

    factory.Credentials.Windows.ClientCredential =
       new System.Net.NetworkCredential(name, password, domain);
    
    6 回复  |  直到 8 年前
        1
  •  11
  •   Ruben Bartelink    11 年前

    不幸的是,您不能在配置文件中指定您的凭据-您必须在代码中这样做(很可能是因为否则,您最终可能会在配置文件中以纯文本形式使用凭据-这不是一件好事….)。

        2
  •  18
  •   Steven    14 年前
    Svc.ClientCredentials.UserName.UserName = AppSettings["WCFSvcUsername"];
    Svc.ClientCredentials.UserName.Password = AppSettings["WCFSvcPassword"];
    

    是不正确的。它与 消息安全性 clientCredentialType=“用户名” . 你应该使用

    Svc.ClientCredentials.Windows.ClientCredential = new NetworkCredential(...);
    
        3
  •  5
  •   Sebastian Castaldi    13 年前

    似乎无法在默认绑定配置中设置ID和密码(我仍在查找),我添加了下面的代码,但仍希望Microsoft将其添加到默认绑定中。

        <appSettings>
         <add key="user"  value="user" />
         <add key="password"  value="password" />
         <add key="domain"  value="domain" />
       </appSettings>
    
    
       // client side code
       string userName =  ConfigurationManager.AppSettings.Get("user");
       string pswd = ConfigurationManager.AppSettings.Get("password");
       string domain = ConfigurationManager.AppSettings.Get("domain");
    
       client.ClientCredentials.Windows.ClientCredential.Domain = domain; 
       client.ClientCredentials.Windows.ClientCredential.UserName = userName;
       client.ClientCredentials.Windows.ClientCredential.Password = pswd;
    

    塞巴斯蒂安·卡斯塔尔迪

        4
  •  4
  •   Quality Catalyst hrincong    8 年前

    我知道在<binding>标记中没有指定凭据的机制,但为什么不这样做:

     Svc.ClientCredentials.UserName.UserName = AppSettings["WCFSvcUsername"];
     Svc.ClientCredentials.UserName.Password = AppSettings["WCFSvcPassword"];
    
        5
  •  1
  •   Cᴏʀʏ bcherry    11 年前
    Svc.ClientCredentials.Windows.ClientCredential = 
        System.Net.CredentialCache.DefaultNetworkCredentials;
    
        6
  •  0
  •   Ryan Rauh    15 年前

    你试过这个吗?

    <system.web>
          <identity impersonate="true" userName="username" password="password"/>
    </system.web>