POST 使用 HttpClient 从内容类型 application/x-www-form-urlencoded 使用 grant_type 和范围
POST using HttpClient fro content type application/x-www-form-urlencoded using grant_type and scope
我正在尝试使用以下代码从端点获取令牌。
var bodyContents = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "userName", "loremipsum" },
{ "password", "xxxxxxx"},
{ "scope", "read_rulesengine write_rulesengine" }
};
string responseContents = string.Empty;
var client = new HttpClient();
client.BaseAddress = new Uri("https://test-sts-dev.test.com");
var req = new HttpRequestMessage(HttpMethod.Post, "/oauth/ls/connect/token");
req.Content = new FormUrlEncodedContent(bodyContents);
var postResponse = await client.SendAsync(req);
postResponse.EnsureSuccessStatusCode();
if (!postResponse.IsSuccessStatusCode)
throw new HttpRequestException("Access denied by token issuer. Check credentials in <encryptedSettings> of config file and try again.");
responseContents = postResponse.Content.ReadAsStringAsync().Result;
var responseObject = JObject.Parse(responseContents);
return responseObject.Value<string>("access_token");
现在我认为我所做的一切都是正确的,但我得到的回应是 BadRequest
以下是我得到的回复:
{Method: POST, RequestUri: 'https://test-sts-dev.test.com/oauth/ls/connect/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
Content-Type: application/x-www-form-urlencoded
Content-Length: 125
}}
我们会发现我缺少请求中的授权设置:
req.Headers.Add("Authorization", "Basic " + auth); // auth will be string visible in postman after Basic
放置这个开始给我结果。
我正在尝试使用以下代码从端点获取令牌。
var bodyContents = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "userName", "loremipsum" },
{ "password", "xxxxxxx"},
{ "scope", "read_rulesengine write_rulesengine" }
};
string responseContents = string.Empty;
var client = new HttpClient();
client.BaseAddress = new Uri("https://test-sts-dev.test.com");
var req = new HttpRequestMessage(HttpMethod.Post, "/oauth/ls/connect/token");
req.Content = new FormUrlEncodedContent(bodyContents);
var postResponse = await client.SendAsync(req);
postResponse.EnsureSuccessStatusCode();
if (!postResponse.IsSuccessStatusCode)
throw new HttpRequestException("Access denied by token issuer. Check credentials in <encryptedSettings> of config file and try again.");
responseContents = postResponse.Content.ReadAsStringAsync().Result;
var responseObject = JObject.Parse(responseContents);
return responseObject.Value<string>("access_token");
现在我认为我所做的一切都是正确的,但我得到的回应是 BadRequest
以下是我得到的回复:
{Method: POST, RequestUri: 'https://test-sts-dev.test.com/oauth/ls/connect/token', Version: 1.1, Content: System.Net.Http.FormUrlEncodedContent, Headers:
{
Content-Type: application/x-www-form-urlencoded
Content-Length: 125
}}
我们会发现我缺少请求中的授权设置:
req.Headers.Add("Authorization", "Basic " + auth); // auth will be string visible in postman after Basic
放置这个开始给我结果。