我试图调用Web API来验证登录。这是有效的,标头响应包含.ASPXAuth。当我在Web API上调用下一个方法时,我得到的是403。
为了解决这个问题,我尝试从auth响应的标头中获取.ASPXAuth身份验证,并将其添加到下一个请求的标头中(如下所示)。
IHttpContent content = new HttpStringContent(@"{ ""domain"": ""DomainName"", ""username"": ""theUserName"", ""password"": ""thePassword"" }", UnicodeEncoding.Utf8, "application/json");
// Send
using (var client = new Windows.Web.Http.HttpClient.HttpClient())
{
var result = await client.PostAsync(new Uri("https://192.168.1.112/api/auth/login"), content);
result.EnsureSuccessStatusCode();
var authResult = await result.Content.ReadAsStringAsync();
client.DefaultRequestHeaders.Add("set-cookie", result.Headers["set-cookie"]);
var itemResult = client.GetAsync(new Uri("https://192.168.1.112/api/item/{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}"));
var itemData = itemResult.GetResults();
}
答案 0 :(得分:0)
我已使用以下代码修复了该问题。
验证并返回身份验证cookie
public async Task<HttpCookie> AuthenticateAsync()
{
var filter = new HttpBaseProtocolFilter();
using (var client = new HttpClient(filter))
{
var authDetails = BuildJsonAuthDetails();
var authResult = await client.PostAsync(new Uri(BaseUrl + "/auth/login"), authDetails);
authResult.EnsureSuccessStatusCode();
return filter.CookieManager.GetCookies(new Uri(BaseUrl + "/auth/login")).FirstOrDefault(x => x.Name == ".ASPXAUTH");
}
}
使用下一篇文章传递Auth cookie
public async Task<string> GetUserDetailsAsync(string userUniqueIdentifier, HttpCookie authCookie)
{
var filter = new HttpBaseProtocolFilter();
filter.CookieManager.SetCookie(authCookie);
using (var client = new HttpClient(filter))
{
var itemResult = await client.GetAsync(new Uri(BaseUrl + "/Person/" + userUniqueIdentifier));
itemResult.EnsureSuccessStatusCode();
return = await itemResult.Content.ReadAsStringAsync();
}
}