如何使用 HttpClient 以 Post 进行身份验证
How to use HttpClient to Post with Authentication
我正在尝试使用 HttpClient 在 C# 中执行以下 curl(对我有用)。
curl -X POST http://www.somehosturl.com \
-u <client-id>:<client-secret> \
-d 'grant_type=password' \
-d 'username=<email>' \
-d 'password=<password>' \
-d 'scope=all
C#代码:
HttpClientHandler handler = new HttpClientHandler { Credentials = new
System.Net.NetworkCredential ("my_client_id", "my_client_secret")
};
try
{
using(var httpClient = new HttpClient(handler))
{
var activationUrl = "www.somehosturl.com";
var postData = "grant_type=password&username=myemail@myemail.com&password=mypass&scope=all";
var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(activationUrl, content);
if(!response.IsSuccessStatusCode)
return null;
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
catch(Exception)
{
return null;
}
执行的时候直接崩溃,连异常都没有捕捉到
通常我能够 GET 并且 POST 非常好,但让我失望的是如何设置身份验证内容(客户端 ID 和客户端密码)
尝试将您的凭据直接放入 HttpClient 的 headers 属性。
using (var client = new HttpClient()) {
var byteArray = Encoding.ASCII.GetBytes("my_client_id:my_client_secret");
var header = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
return await client.GetStringAsync(uri);
}
首先,您必须使用 <clientid>
和 <clientsecret>
设置 Authorization
-Header。
您应该使用 FormUrlEncodedContent
而不是 StringContent
,如下所示:
var client = new HttpClient();
client.BaseAddress = new Uri("http://myserver");
var request = new HttpRequestMessage(HttpMethod.Post, "/path");
var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
formData.Add(new KeyValuePair<string, string>("username", "<email>"));
formData.Add(new KeyValuePair<string, string>("password", "<password>"));
formData.Add(new KeyValuePair<string, string>("scope", "all"));
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);
见BasicAuthenticationHeaderValue
httpClient.DefaultRequestHeaders.Authorization
= new BasicAuthenticationHeaderValue("login", "password");
或使用 IdentityModel 的扩展:
<PackageReference Include="IdentityModel" Version="4.0.0" />
var client = new HttpClient();
client.SetBasicAuthentication(login, password);
client.SetBearerToken(token);
我正在尝试使用 HttpClient 在 C# 中执行以下 curl(对我有用)。
curl -X POST http://www.somehosturl.com \
-u <client-id>:<client-secret> \
-d 'grant_type=password' \
-d 'username=<email>' \
-d 'password=<password>' \
-d 'scope=all
C#代码:
HttpClientHandler handler = new HttpClientHandler { Credentials = new
System.Net.NetworkCredential ("my_client_id", "my_client_secret")
};
try
{
using(var httpClient = new HttpClient(handler))
{
var activationUrl = "www.somehosturl.com";
var postData = "grant_type=password&username=myemail@myemail.com&password=mypass&scope=all";
var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(activationUrl, content);
if(!response.IsSuccessStatusCode)
return null;
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
catch(Exception)
{
return null;
}
执行的时候直接崩溃,连异常都没有捕捉到
通常我能够 GET 并且 POST 非常好,但让我失望的是如何设置身份验证内容(客户端 ID 和客户端密码)
尝试将您的凭据直接放入 HttpClient 的 headers 属性。
using (var client = new HttpClient()) {
var byteArray = Encoding.ASCII.GetBytes("my_client_id:my_client_secret");
var header = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
return await client.GetStringAsync(uri);
}
首先,您必须使用 <clientid>
和 <clientsecret>
设置 Authorization
-Header。
您应该使用 FormUrlEncodedContent
而不是 StringContent
,如下所示:
var client = new HttpClient();
client.BaseAddress = new Uri("http://myserver");
var request = new HttpRequestMessage(HttpMethod.Post, "/path");
var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
formData.Add(new KeyValuePair<string, string>("username", "<email>"));
formData.Add(new KeyValuePair<string, string>("password", "<password>"));
formData.Add(new KeyValuePair<string, string>("scope", "all"));
request.Content = new FormUrlEncodedContent(formData);
var response = await client.SendAsync(request);
见BasicAuthenticationHeaderValue
httpClient.DefaultRequestHeaders.Authorization
= new BasicAuthenticationHeaderValue("login", "password");
或使用 IdentityModel 的扩展:
<PackageReference Include="IdentityModel" Version="4.0.0" />
var client = new HttpClient();
client.SetBasicAuthentication(login, password);
client.SetBearerToken(token);