[英]How to apply basic authentication in WCF?
我正在實施 WcfClientFactory
public class WcfClientFactory : IDisposable
{
internal const string WildcardConfigurationName = "*";
//We track all channels created by this instance so they can be destroyed
private readonly List<WeakReference<IDisposable>> _disposableItems = new List<WeakReference<IDisposable>>();
public T CreateClient<T>(string configurationName = WildcardConfigurationName, string address=null)
{
var factory = new ChannelFactory<T>(configurationName);
if (!string.IsNullOrWhiteSpace(address))
{
factory.Endpoint.Address = new EndpointAddress(address);
}
var channel = factory.CreateChannel();
var clientChannel = (IClientChannel)channel;
clientChannel.Open();
_disposableItems.Add(new WeakReference<IDisposable>(clientChannel,false));
return channel;
}
void IDisposable.Dispose()
{
//No finalizer is implemented as there are no directly held scarce resources.
//Presumably the finalizers of items in disposableItems will handle their own teardown
//if it comes down to it.
foreach (var reference in _disposableItems)
{
IDisposable disposable;
if (reference.TryGetTarget(out disposable))
{
disposable.Dispose();
}
}
}
}
所以我可以創建一個 WCF clientChannel
var client = _wcfClientFactory.CreateClient<ICrmService>(address);
如果 WCF 沒有任何身份驗證,它工作正常。 現在,我們要向該工廠添加身份驗證。 我該怎么做? 我試過下面的代碼
public T CreateClientWithBasicAuthentication<T>(string address)
{
WSHttpBinding myBinding = new WSHttpBinding();
myBinding.Security.Mode = SecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
var channel = factory.CreateChannel();
var clientChannel = (IClientChannel)channel;
////CrmServiceClient csc = (CrmServiceClient)channel;
////csc.ClientCredentials.UserName.UserName = _UserName;
////csc.ClientCredentials.UserName.Password = _Password;
clientChannel.Open();
_disposableItems.Add(new WeakReference<IDisposable>(clientChannel, false));
return channel;
}
但它會生成異常並要求輸入用戶名和密碼。 如何設置密碼和用戶名?
變量factory有一個Credential成員,不過是get only。 這就是為什么我認為它必須是一種在調用 CreateChannel 之前設置憑據的方法
謝謝
這里的描述可能有問題,你的想法是對的,這里我們可以設置客戶端的認證憑證。
var factory = new ChannelFactory<T>(myBinding, new EndpointAddress(address));
//for HttpClientCredentialType.Basic
factory.Credentials.UserName.UserName = "administrator";
factory.Credentials.UserName.Password = "abcd1234!";
//for window credentials
//factory.Credentials.Windows.ClientCredential.UserName = "adminsitrator";
//factory.Credentials.Windows.ClientCredential.Password = "abcd1234!";
var channel = factory.CreateChannel();
此外,請注意通道工廠使用的綁定類型應與服務器端的綁定類型保持一致。
如果問題仍然存在,請隨時告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.