wcf - 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;
}
}
解决方案
根据您提供的错误消息,我认为这可能是因为您的自定义标头未成功添加到消息中。我认为您可以尝试使用 OperationContextScope 添加自定义标头。此链接中有一个示例。你可以参考它:
使用 OperationContextScope 设置标头时,IClientMessageInspector BeforeSendRequest 方法不起作用
推荐阅读
- javascript - 测试智能合约时 Mocha 中的断言错误
- python - 基于字符串的部分匹配访问系列值
- laravel - laravel 7 是否有一种获取所有列列表的方法?
- firebase - StreamBuilder 在快照中不返回任何内容
- python - 如何索引张量并更改值
- curl - 即使服务器返回 500,也打印 HTTP 响应正文
- scala - 列表的Scala匹配模式
- python - 如何确定一个元组是否是另一个元组的切片(不仅仅是一个子集!)
- angular - 强制子调用父方法
- javascript - 升级到 Angular 10 - 修复 CommonJS 或 AMD 依赖项可能导致优化救助