0

I am using C#, RestSharp to get the bearer token for a sap exposed RestAPI. Here is my code snippet

        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);

But no luck - always get below error

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

I used the psotman with same credentials and it worked fine!! Any idea?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
deb
  • 145
  • 1
  • 2
  • 11
  • See this [question](https://stackoverflow.com/questions/45238899/restsharp-post-request-body-with-x-www-form-urlencoded-values) – Max Nov 07 '18 at 18:46
  • not sure if this is an issue with RestSharp .. i just used RestAsured with Java and Postman and all worked !! – deb Nov 08 '18 at 12:12

1 Answers1

1

You might need to use the Authenticator property. Try this

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);
Doga
  • 281
  • 2
  • 11