【问题标题】:Passing .ASPXAuth authentication cookie using Windows.Web.Http.HttpClient使用 Windows.Web.Http.HttpClient 传递 .ASPXAuth 身份验证 cookie
【发布时间】:2016-01-12 18:41:51
【问题描述】:

我正在尝试调用 Web API 来验证登录。这是有效的,并且标头响应包含 .ASPXAuth。当我在 Web API 上调用下一个方法时,我得到了 403。

为了解决这个问题,我尝试从身份验证响应的标头中获取 .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();

                }

【问题讨论】:

  • 可能响应(又名result)不包含Set-Cookie 标头。 Set-Cookie 用于请求,Cookie 用于响应,但每个标头的格式不同,如果响应中存在,则需要对其进行解析。

标签: c# asp.net-web-api asp.net-membership httpclient win-universal-app


【解决方案1】:

我已经用下面的代码解决了这个问题。

验证并返回 auth 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();
                }
            }

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多