首页 > 解决方案 > WCF 客户端调用 api 与承载令牌(.net 核心 3.1) - 未经授权的调用

问题描述

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

MessageSecurityException:HTTP 请求未经客户端身份验证方案“匿名”授权。从服务器收到的身份验证标头是“”。

我已验证订阅密钥和令牌与 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)
    {
    }
}

并使用以下代码添加标题

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;
    }
} 

标签: wcf.net-core

解决方案


根据您提供的错误消息,我认为这可能是因为您的自定义标头未成功添加到消息中。我认为您可以尝试使用 OperationContextScope 添加自定义标头。此链接中有一个示例。你可以参考它:

使用 OperationContextScope 设置标头时,IClientMessageInspector BeforeSendRequest 方法不起作用


推荐阅读