如何解决具有Bearer令牌的WCF客户端调用api.net core 3.1-未经授权的调用
我试图调用一个SOAP api,该api需要一个承载授权令牌和一个来自.net核心的订阅密钥,但是我遇到了以下我不理解的异常。
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添加自定义标头。此链接中有一个示例。您可以参考它:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。