简体   繁体   中英

Consuming REST Service with WCF - Basic Authentication

I'm trying to consume a REST service with Basic Authentication with an odd problem. The first request made does not include the basic authentication credentials specified. This happens for every first request made. It happens every time the application starts. It does not happen for subsequent requests. I am using the ClientBase<T> class to call the API, which looks something like this:

public class MyApi : ClientBase<IMyApi>
{
    protected override IMyApi CreateChannel()
    {
        //Remove all client credentials. 
        ChannelFactory.Endpoint.Behaviors.RemoveAll<ClientCredentials>();

        //Create new client credentials and add to the endpoint behaviours.
        ClientCredentials clientCredentials = new ClientCredentials();
        clientCredentials.UserName.UserName = Username;
        clientCredentials.UserName.Password = Password;
        ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);

        return base.CreateChannel();
    }

    public MyApi() : base (DefaultEndpointName)
    {}
}

My binding is setup as follows:

  <customBinding>        
    <binding name="myApiBinding">
      <webMessageEncoding webContentTypeMapperType="ContentTypeMapper,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <httpTransport manualAddressing="true" maxReceivedMessageSize="6553600" authenticationScheme="Basic" realm="myRealm" />
    </binding>
  </customBinding>

I have tried bumping the project up to .Net 4, adding the client credentials after initialising the API, but none seem to have the desired the effect.

Is there a way to get the credentials added for every request?

See this question .

The first answer explains why... (The server should be responding to the first request with an authentication challenge)

The second answer explains how to work around... (By manipulating request http header to manually insert the basic authentication credentials)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM