【问题标题】:WCF client call api with Bearer token (.net core 3.1) - unauthorized callWCF 客户端调用 api 与承载令牌(.net 核心 3.1) - 未经授权的调用
【发布时间】:2020-10-26 15:40:19
【问题描述】:

我正在尝试调用一个需要不记名授权令牌和来自 .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;
    }
} 

【问题讨论】:

  • 我认为这可能是因为您的自定义标头未成功添加到邮件中。我认为您可以尝试使用 OperationContextScope 添加自定义标头。此链接中有一个示例。可以参考:stackoverflow.com/questions/62344937/…

标签: wcf .net-core


【解决方案1】:

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

IClientMessageInspector BeforeSendRequest method is not working when setting header using OperationContextScope

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2019-08-14
    相关资源
    最近更新 更多