使用 Bearer 令牌 (.net core 3.1) 的 WCF 客户端调用 api - 未经授权的调用

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

我正在尝试调用 soap api,它需要不记名授权令牌和来自 .net core 的订阅密钥,但我收到以下我不理解的异常。

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

我已验证订阅密钥和令牌可用于 SoapUI。这是 SoapUI 调用:

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>

这是我调用端点的代码:

        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");

使用测试端点行为

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)
    {
    }
}

并在下面的代码中添加 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;
    }
} 

根据您提供的错误信息,我认为这可能是因为您的自定义 headers 没有成功添加到邮件中。我想你可以尝试使用 OperationContextScope 添加自定义 headers。在这个link中有一个例子。可以参考一下:

IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope