Xbox One使用Windows.Web.Http.HttpClient遇401未授权错误排查
问题描述
我在Xbox One上使用Windows.Web.Http.HttpClient时遇到了异常的401未授权错误,但在普通Windows设备上一切运行正常。确认凭证信息完全无误,并且已经在3台不同的Xbox One设备上测试过,结果完全一致。
相关实现代码如下:
Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter(); filter.AllowUI = false; filter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache; filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.NoCache; Uri uri = new Uri("http://" + url + ":" + port + endpoint); if (username != "" && password != "") filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(uri.OriginalString, username, password); try { HttpClient client = new HttpClient(filter); HttpResponseMessage response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); var buffer = await response.Content.ReadAsBufferAsync(); var byteArray = buffer.ToArray(); return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); } catch { return null; }
我已经硬编码了用户名和密码来排除输入错误的可能,以下是Fiddler抓包的输出结果:
Xbox One 抓包结果:
GET http://192.168.178.31:XXXX/XXX/XXX HTTP/1.1 Accept-Encoding: gzip, deflate Host: 192.168.178.31:XXXX Connection: Keep-Alive Pragma: no-cache HTTP/1.1 401 Unauthorized Server: XXXX Cache-Control: no-cache WWW-Authenticate: Digest realm="XXXX", qop="auth", nonce="516f32c0f120024c220873c1ebc159e4", opaque="2effb29f8b3de0ca6a688330875890c8" Connection: Keep-Alive Content-Type: text/html Content-Length: 432
Windows 设备抓包结果:
GET http://192.168.178.31:XXXX/XXX/XXX HTTP/1.1 Accept-Encoding: gzip, deflate Host: 192.168.178.31:XXXX Connection: Keep-Alive Pragma: no-cache HTTP/1.1 200 OK
之后我又编写了一个使用System.Net.Http而非Windows.Web.Http的小型测试应用,Fiddler抓包结果如下:
Windows 设备:
HTTP 401 Text/Html HTTP 200 Text/x-json
Xbox One:
HTTP 401 Text/Html HTTP 401 Text/Html
临时解决方案
目前我采用了双重认证尝试的方案,当一种认证方式失败时自动切换到另一种:
if (!digestFailed) filter.ServerCredential = new Windows.Security.Credentials.PasswordCredential(uri.OriginalString, username, password); else request.Headers.Authorization = new HttpCredentialsHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));
但Xbox One的问题显然很严重:当服务器设置为仅Digest认证时,Xbox One完全无法建立连接!我推测Xbox平台上使用Windows.Security.Credentials.PasswordCredential生成Digest凭证的过程存在底层问题。
为了更清晰地展示问题,我整理了不同认证模式下的测试结果:
- 服务器采用Basic认证:
- Windows设备:正常
- Xbox One:正常
- 服务器采用Digest认证:
- Windows设备:正常
- Xbox One:失败
- 服务器采用Digest+Basic混合认证:
- Windows设备:正常(自动使用Digest认证通过)
- Xbox One:正常(自动切换为Basic认证通过)
内容的提问来源于stack exchange,提问作者Peter Frommert
相关产品推荐
相关产品推荐

