post - POST 使用 HttpClient 来自内容类型 application/x-www-form-urlencoded 使用 grant_type 和 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
放置这个开始给我结果。
推荐阅读
- javascript - 树枝 foreach 中的 JavaScript 函数
- mysql - 如何将 RDS Aurora Mysql 数据库复制到只有一些行的 RDS 的其他实例
- arrays - Typescript 函数,它从具有正确类型的数组中返回一项
- swift - Swift:为什么我们需要 keypath
- javascript - 删除 Wordpress 上每个文档开头的两行 JS 代码
- database - YugaByte 创建数据库失败
- python-3.x - 我可以成功安装python包但无法导入它。未找到符号。预计在:
- selenium - 无法注册此节点:发送注册请求时出错:尝试将 Selenium Grid 节点连接到 Selenium Grid Hub 时连接失败
- c++ - 使用 DER 二进制私钥签署 SHA256 哈希
- angularjs - 从多个复选框中获取值作为字符串