【问题标题】:POST using HttpClient fro content type application/x-www-form-urlencoded using grant_type and scopePOST 使用 HttpClient 来自内容类型 application/x-www-form-urlencoded 使用 grant_type 和 scope
【发布时间】:2019-05-01 09:06:54
【问题描述】:

我正在尝试使用以下代码从端点获取令牌。

 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
}}

【问题讨论】:

    标签: post httpclient httpresponse


    【解决方案1】:

    我们会发现我缺少请求中的授权设置:

    req.Headers.Add("Authorization", "Basic " + auth); // auth will be string visible in postman after Basic
    

    放置这个开始给我结果。

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 1970-01-01
      • 2020-04-21
      • 2018-04-04
      • 2018-11-17
      • 2014-03-30
      • 2021-02-03
      • 2015-04-02
      相关资源
      最近更新 更多