调用 API 的 HttpClient 未通过 cookie 身份验证

HttpClient calling API doesnt not pass cookie auth

尝试使用 HttpClient 从控制器调用 API 并且 API 无法识别用户已通过身份验证和登录。从 JS 调用 API 时我没有问题。我注意到 HttpClient 仅通过 HTTP 1.1 发送,因此我将 DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER 标志升级到 2.0 设置,但这没有任何区别。我已经尝试了 HttpClientHandler 属性的所有组合,包括 UseCookies,但请求从未经过身份验证。

        using (var handler = new HttpClientHandler {UseDefaultCredentials = true})
        {
            using (var httpClient = new HttpClient(handler))
            {
                var response = httpClient.GetStringAsync(new Uri($"https://localhost:64366/api/")).Result;
            }
        }

将来会转向基于令牌的身份验证,但现在想了解为什么从 C# 调用 API 与从 JS 调用之间存在差异。这是本地主机上的所有 HTTPS,使用 asp net core 2.2.

JS 和 C# 的区别在于浏览器会自动将 cookie 附加到请求中,而您必须在 C# 中手动附加 cookie,如 juunas 所述。

要获取和使用身份验证 cookie,您可以使用以下模式

CookieContainer cookies = new CookieContainer(); //this container saves cookies from responses and send them in requests
var handler = new HttpClientHandler
{
    CookieContainer = cookies
};

var client = new HttpClient(handler);

string authUrl = ""; //your auth url
string anyUrl = ""; //any url that requires you to be authenticated

var authContent = new FormUrlEncodedContent(
    new List<KeyValuePair<string, string>> {
        new KeyValuePair<string, string>("login", "log_in"),
        new KeyValuePair<string, string>("password", "pass_word")
        }
    );

//cookies will be set on this request
HttpResponseMessage auth = await client.PostAsync(authUrl, authContent);
auth.EnsureSuccessStatusCode(); //retrieving result is not required but you will know if something goes wrong on authentication

//and here retrieved cookies will be used
string result = await client.GetStringAsync(anyUrl);