HttpClient调用API不会通过Cookie身份验证

时间:2019-01-27 19:42:09

标签: c# asp.net-core asp.net-authentication

尝试使用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#与JS调用API之间会有区别。这就是使用asp net core 2.2的localhost上的所有HTTPS。

1 个答案:

答案 0 :(得分:1)

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

要获取和使用身份验证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);