Search code examples
wcf.net-core

WCF client call api with Bearer token (.net core 3.1) - unauthorized call


I am trying to call a soap api that requires a bearer authorization token and a subscription key from .net core but I am getting the following exception that I don't understand.

MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was ''.

I have verified that the subscription key and token is working with SoapUI. This is the SoapUI call:

POST {{URL}} HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "{{ACTION}}"
Authorization: Bearer Tplen
Subscription-Key: {{KEY}}
Content-Length: 343
Host: {{HOST}}
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.5 (Java/12.0.1)

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="{{REPLACED}}">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:REPLACED>
         <!--Optional:-->
         <ser:REPLACED>VALUE</ser:REPLACED>
      </ser:REPLACED>
   </soapenv:Body>
</soapenv:Envelope>

This is my code to call the endpoint:

        var binding = new BasicHttpsBinding();
        var factory = new ChannelFactory<ITestContractChannel>(binding, new EndpointAddress(url));
        factory.Endpoint.EndpointBehaviors.Add(new Test());
        var channel = factory.CreateChannel();
        var result = await channel.GetTestAsync("1");

Using Test endpoint behavior

public class Test : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add(new TestHeaderInspector());
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

And following code to add the headers

public class TestHeaderInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        var httpRequestMessage = new HttpRequestMessageProperty();
        httpRequestMessage.Headers.Add("Subscription-Key", key);
        httpRequestMessage.Headers.Add("Authorization", "Bearer "+ token);
        request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
        return null;
    }
} 

Solution

  • According to the error message you provided, I think this may be because your custom headers were not successfully added to the message. I think you can try to use OperationContextScope to add custom headers. There is an example in this link. You can refer to it:

    IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope