You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms中HttpClient Windows认证返回401问题排查

Xamarin.Forms 客户端调用IIS Windows认证接口返回401故障

问题背景

  • 为Xamarin.Forms应用开发登录模块时,出现仅应用内代码发起请求时Windows Authentication无法生效的问题:通过Postman、普通浏览器访问对应Web服务均可正常返回结果,此前对接同服务使用Basic Authentication时功能运行稳定无异常
  • 对应Web服务部署在IIS 8.5服务器上

初始实现代码如下:

public async Task<bool> GetLoginAccess(UserCredential userCredentials)
{
    HttpClientHandler authHandler = new HttpClientHandler()
    {
        PreAuthenticate = true,
        AllowAutoRedirect = true,
        UseDefaultCredentials = true
    };
    using (HttpClient client = new HttpClient(authHandler))
    {
        _client.BaseAddress = new Uri(Properties.Resources.URL_Webservice_Login);
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        var response = await _client.GetAsync("api/LoginChecker?application=***&user=***").ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            var access = JsonConvert.DeserializeObject<bool>(json);
            return access;
        }
        else
        {
            return false;
        }
    }
}

上述代码发起请求固定返回401 Unauthorized错误,响应详情如下:

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Tue, 14 Jun 2022 08:21:30 GMT
  Server: Microsoft-IIS/8.5
  WWW-Authenticate: Negotiate
  WWW-Authenticate: NTLM
  X-Android-Received-Millis: 1655194890132
  X-Android-Response-Source: NETWORK 401
  X-Android-Selected-Protocol: http/1.1
  X-Android-Sent-Millis: 1655194890044
  X-Powered-By: ASP.NET
  Content-Length: 1344
  Content-Type: text/html
}}

调整尝试

针对初始代码的问题做如下修改:

  • 显式构造NetworkCredential对象,传入用户名、密码与域标识DOM
  • 关闭UseDefaultCredentials配置,将构造好的凭据赋值给HttpClientHandler的Credentials属性
  • 修正BaseAddress与请求路径的拼接配置

调整后代码如下:

var credentialsCache = new NetworkCredential(userCredentials.User, userCredentials.Password, "DOM");
HttpClientHandler authHandler = new HttpClientHandler()
{
    PreAuthenticate = true,
    Credentials = credentialsCache,
    AllowAutoRedirect = true,
    UseDefaultCredentials = false
};
using (HttpClient client = new HttpClient(authHandler, true))
{
    client.BaseAddress = new Uri(Properties.Resources.URL_Webservice_Login);
    
    var response = await _client.GetAsync("/api/LoginChecker?application=***&user=***");
    if (response.IsSuccessStatusCode)
    {
        // 原有业务处理逻辑
    }
}

调整后请求依然返回认证失败。后续验证确认:通过安卓模拟器、实体安卓设备自带浏览器直接访问服务对应页面,手动输入域账号凭据可正常通过认证,排除服务端配置、网络连通性、账号权限问题,确认故障点在客户端代码实现层面。

最终解决

多轮排查未定位到HttpClient相关配置的问题点,更换为WebClient实现接口请求逻辑后,Windows Authentication功能可正常运行。

内容的提问来源于stack exchange,提问作者Bucks34

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:45:36