Windows.Web.Http.HttpClient + WEB API Windows Authentication Windows.Web.Http.HttpClient和WEB API Windows身份验证

3
我正在使用Windows.Web.Http.HttpClient连接到我的WEB API。应用程序没有提示用户名和密码,但最近我将AuthorizeAttribute过滤器从操作移动到类级别更改了WEB API。现在,我的Windows store 8.1应用程序会提示输入用户名和密码。请告诉我如何设置HttpClient以不提示登录和密码。有人能建议我是否需要添加头文件到我的httpcleint中吗?
使用(Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient()) { // 添加用户代理标头 var headers = httpClient.DefaultRequestHeaders; }
//安全的方法是通过TryParseAdd方法检查来自用户的标头值 //由于我们知道这个标头是好的,所以我们使用ParseAdd,会抛出一个异常- //如果是无效的值,则会使用http://msdn.microsoft.com/en-us/library/windows/apps/dn440594.aspx
                headers.UserAgent.ParseAdd("ie");
                headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");


                using (var response = await httpClient.GetAsync(new Uri(url)))

我看不到发送默认凭据的方法。

2个回答

12

使用HttpBaseProtocolFilter.AllowUI禁用 UI 对话框。尝试这样做:

禁用 UI 对话框,可以使用HttpBaseProtocolFilter.AllowUI。请尝试以下操作:

Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
    new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;
HttpClient client = new HttpClient(filter);

Uri uri = new Uri("http://localhost/?basic=1");
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);

您需要凭证吗?请使用HttpBaseProtocolFilter.ServerCredential。尝试这样做:

Uri uri = new Uri("http://localhost?ntlm=1");

Windows.Web.Http.Filters.HttpBaseProtocolFilter filter =
    new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.AllowUI = false;

// Set credentials that will be sent to the server.
filter.ServerCredential =
    new Windows.Security.Credentials.PasswordCredential(
        uri.ToString(),
        "userName",
        "abracadabra");

HttpClient client = new HttpClient(filter);
var response = await client.GetAsync(uri);
System.Diagnostics.Debug.WriteLine(response);

您是否需要默认的 Windows 凭据(域凭据)?只需将 Enterprise Authentication 能力添加到您的 Package.appxmanifest 中即可。


0

我尝试应用您的解决方案,但它并没有按预期工作,或者可能是因为我不理解我应该做什么。 我需要使用Windows凭据,并在我的UWP应用程序中启用了企业身份验证功能。

我使用您建议的代码:

var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.PostAsync(concUri, null);

但是响应返回了一个401.3错误...

如果我将登录/密码添加到ServerCredential中,这将正常工作:

var filter = new HttpBaseProtocolFilter();
filter.AllowUI = false;
filter.ServerCredential  = new Windows.Security.Credentials.PasswordCredential(WebServiceConstants.WebServiceUrl.ToString(), "login", "password");
var client = new HttpClient(filter);
HttpResponseMessage response = new HttpResponseMessage();
response = await client.GetAsync(concUri);

但是我不明白在这种情况下企业身份验证的作用是什么,如果我需要传递登录名和密码...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接