【发布时间】: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/…