擴展在拉吉斯拉夫Mrnka的答案,你可能會發現這個實現有用:
public class UserNameClientCredentials : ClientCredentialsElement
{
private ConfigurationPropertyCollection properties;
public override Type BehaviorType
{
get { return typeof (ClientCredentials); }
}
/// <summary>
/// Username (required)
/// </summary>
public string UserName
{
get { return (string) base["userName"]; }
set { base["userName"] = value; }
}
/// <summary>
/// Password (optional)
/// </summary>
public string Password
{
get { return (string) base["password"]; }
set { base["password"] = value; }
}
protected override ConfigurationPropertyCollection Properties
{
get
{
if (properties == null)
{
ConfigurationPropertyCollection baseProps = base.Properties;
baseProps.Add(new ConfigurationProperty(
"userName",
typeof (String),
null,
null,
new StringValidator(1),
ConfigurationPropertyOptions.IsRequired));
baseProps.Add(new ConfigurationProperty(
"password",
typeof (String),
""));
properties = baseProps;
}
return properties;
}
}
protected override object CreateBehavior()
{
var creds = (ClientCredentials) base.CreateBehavior();
creds.UserName.UserName = UserName;
if (Password != null) creds.UserName.Password = Password;
ApplyConfiguration(creds);
return creds;
}
}
在這之後,你需要註冊使用的東西這個自定義實現像
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="UserNameClientCredentials" type="MyNamespace.UserNameClientCredentials, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
...
謝謝。但是將憑據存儲在AppSettings中仍然需要我以編程方式設置值。我確定這可能是一個安全問題,但我只是沒有看到其中的區別:無論如何,人們會將登錄/密碼存儲在某處 - 爲什麼不與其他WCF配置一起存儲? :) – 2010-09-16 14:03:54
正如你所說,它與安全有關。向用戶提供以明文形式指定密碼的方法是一個明顯的安全漏洞。現在,如果開發人員決定用我提供的代碼繞過它,他會意識到他做錯了。他不能說「嘿,微軟,你的錯,你說它可以放入WCF配置。」 – 2010-09-16 16:40:47