c# - 使用 HttpClient.GetAsync() 使用具有基本身份验证的 WCF REST 服务会导致 (401) 未经授权

标签 c# .net wcf basic-authentication dotnet-httpclient

我尝试使用基本身份验证通过 HttpClient 连接到 WCF 自托管 REST 服务,但不断收到 (401) 未经授权的消息。当我从Web浏览器访问同一端点时,输入相同的用户名和密码会成功。服务端的身份验证是通过UserNamePasswordValidator完成的。为了测试目的,我将 Validate 方法留空,因此所有请求都应该有效。尽管如此,调用 GetAsync() 会导致 (401) Unauthorized。当我在 Validate 方法中设置断点时,我可以检查是否传递了正确的值。对这种行为有什么解释吗?

客户端

using (var httpClient = new HttpClient())
{
    var authString = "admin:admin";
    var authEncoded = Encoding.GetEncoding("ISO-8859-1").GetBytes(authString);
    var authBase64String = Convert.ToBase64String(authEncoded);
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authBase64String);
    httpClient.BaseAddress = new Uri(UriFactory.GetServiceUrl());

    using (var response = await httpClient.GetAsync(serviceDomain))
    {
        string responseData = await response.Content.ReadAsStringAsync();
        return JsonConverter.FromJson<TResponse>(responseData);
    }
}

服务

public class CustomUserNameValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
    }
}

这是服务配置

<system.serviceModel>
<bindings>  
  <webHttpBinding>  
    <binding name="HttpsBinding">  
      <security mode="Transport">  
        <transport clientCredentialType="Basic" />  
      </security>  
    </binding>  
  </webHttpBinding>  
</bindings>  

<services>
  <service behaviorConfiguration="MyServiceBeahvior" name="ServiceImplementation">
    <endpoint address="status"        binding="webHttpBinding" bindingConfiguration="HttpsBinding" contract="Status.IStatusService"            behaviorConfiguration="MyWebBahviorr"/>
    <endpoint address="mex"           binding="mexHttpsBinding" contract="IMetadataExchange" />
    <host>
      <baseAddresses />
    </host>
  </service>
</services>

<behaviors>
  <serviceBehaviors>
    <behavior name="MyServiceBeahvior">
      <serviceMetadata httpsGetEnabled="True" />
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="MyWebBahvior">
      <webHttp automaticFormatSelectionEnabled="false" />
    </behavior>
  </endpointBehaviors>
</behaviors>

_oServiceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
_oServiceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();

通信通过带有自签名证书的 HTTPS 进行。

最佳答案

最后,我能够使用 Fiddler 找到我的问题。我发送的请求没有最后的斜杠(例如 https://localhost:4444/status 而不是 https://localhost:4444/status/ )。 Web 浏览器能够处理重定向,但 HttpClient 失败。

关于c# - 使用 HttpClient.GetAsync() 使用具有基本身份验证的 WCF REST 服务会导致 (401) 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54637195/

相关文章:

C# 用捕获的组替换正则表达式匹配的模式

c# - C# 和 C/C++ 中二进制到 float 转换的区别

c# - 为什么还对 InternalsVisibleTo 引用的程序集进行了签名?

c# - 使用 Microsoft.HttpClient 和 HttpContentExtensions 的通用 POST 请求

c# - log4net ....单独的日志文件

c# - WCF WebHttp 服务中的错误处理,仅带有 WebFaultException xml 格式的异常

c# - 访问 IEnumerable 内部的特定属性

由 c# zedgraph : how to use the cursor property?

c# - 当我从 ApplicationDbContext 调用时外键对象返回 null

java - 加密xml文件