获取Oauth2的令牌-请求消息中的表单参数的UrlDecoding失败。表单参数需要url编码

时间:2018-11-07 03:54:15

标签: c# rest oauth-2.0 token restsharp

我正在使用C#,RestSharp来获取暴露在汁液中的RestAPI的承载令牌。这是我的代码段

        var client = new RestClient("https://url/oauth2/token");
        var request = new RestRequest(Method.POST);
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddHeader("Authorization", "Basic clientusername:clientpassword");

        request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=user&password=pwd", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

但是没有运气-总是低于错误

{"fault":{"faultstring":"UrlDecoding of the form parameters from the request message failed. The form parameters needs to be url encoded","detail":{"errorcode":"steps.oauth.v2.InvalidRequest"}}}

我以相同的凭据使用了psotman,它工作正常!! 有想法吗?

1 个答案:

答案 0 :(得分:0)

您可能需要使用Authenticator属性。试试这个

var client = new RestClient($"{_apiBaseUrl}/token")
        {
            Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)
        };

        var request = new RestRequest(Method.POST);
        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("content-type", "application/x-www-form-urlencoded");
        request.AddParameter("application/x-www-form-urlencoded", $"grant_type=password&username={username}&password={password}&scope=trust", ParameterType.RequestBody);

        var response = client.Execute(request);