How do I get basic security to apply when programmatically creating WebChannel in WCF?
I am creating a WCF channel 开发者_如何学编程for a POX web client in code using the WebChannelFactory
. I have created a binding configuration in my app.config
with basic authentication set, but when I try to connect to the service endpoint, basic security is not being applied and I get a 401 from the server.
The name in my app.config
endpoint configuration and my programmatic declaration match. I can confirm this b/c it's picking up the address correctly.
The service endpoint challenges for BASIC security, but nothing happens.
Do I need to set the wcf client endpointConfiguration?
Code
namespace AccountServices
{
[ServiceContract]
public interface IAccount
{
[OperationContract]
[WebGet(BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Xml, UriTemplate="?resourceId={resourceId}")]
XmlElement GetAccount(string resourceId);
}
public class AccountService
{
public XmlElement GetAccount(string resourceId, string userName, string password)
{
WebChannelFactory<ICPM> factory = new WebChannelFactory<IAccount>("AccountHttpClient");
if (!string.IsNullOrWhiteSpace(userName))
factory.Credentials.UserName.UserName = userName;
if (!string.IsNullOrWhiteSpace(password))
factory.Credentials.UserName.Password = password;
IAccount proxy = factory.CreateChannel();
try
{
return proxy.GetAccount(resourceId);
}
catch (System.ServiceModel.Security.MessageSecurityException securityEx)
{
throw;
}
}
}
}
Config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="RawWebBinding" contentTypeMapper="">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="Basic"
realm="Login" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="pox">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://ENDPOINTADDRESS/"
behaviorConfiguration="pox" binding="webHttpBinding" bindingConfiguration="RawWebBinding"
contract="AccountServices.IAccount" name="AccountHttpClient" kind=""
endpointConfiguration="" />
</client>
</system.serviceModel>
Adding an endpointConfiguration fixed the issue. The authentication header is now being sent across.
...
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="NewStandardEndpoint0">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="Basic"
realm="Login" />
</security>
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
...
<client>
<endpoint address="https://ENDPOINTADDRESS/"
behaviorConfiguration="pox" binding="webHttpBinding" bindingConfiguration="RawWebBinding"
contract="AccountServices.IAccount" name="AccountHttpClient" kind="webHttpEndpoint"
endpointConfiguration="NewStandardEndPoint0" />
</client>
精彩评论