Click here to Skip to main content
15,881,561 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get my OAuth token but getting a Bad request. I am trying to use Dictionary to store in key pair values but its not working.
I have successfully send request using another library using HttpWebResponse and when I check in fidler I get this when I check the raw response..

grant_type=password&username=client@company.com&password=pass&scope=scope1&client_id=api&client_secret=rest


But when I used RestSharp and Execute my code I checked in fidler I get 400 bad request and I see the credential pass as this. How can resolve this??

{"grant_type":"password","username":"client@company.com","password":"pass","scope":"scope1","client_id":"api","client_secret":"rest"}


What I have tried:

Here is my code
[Test]
public void getAccessToken1()
{
    Dictionary<string, string> formParams = new Dictionary<string, string>();
    formParams.Add("grant_type", "password");
    formParams.Add("username", "client@company.com");
    formParams.Add("password", "pass");
    formParams.Add("scope", "scope1");
    formParams.Add("client_id", "api");
    formParams.Add("client_secret", "rest");

    RestClient client = new RestClient("http://example.com/connect/token");
    RestRequest request = new RestRequest() { Method = Method.POST };
    request.AddJsonBody(formParams);
    IRestResponse token = client.Execute(request);


}
Posted
Updated 12-May-20 0:53am

1 solution

You're looking at the request, not the response.

The request which succeeds is sending the parameters encoded as application/x-www-form-urlencoded. The request that fails is sending the parameters encoded as JSON.

You need to add the parameters to the RestRequest object instead of using AddJsonBody:
C#
RestClient client = new RestClient("http://example.com/connect/token");
RestRequest request = new RestRequest() { Method = Method.POST };

request.AddParameter("grant_type", "password", ParameterType.GetOrPost);
request.AddParameter("username", "client@company.com", ParameterType.GetOrPost);
request.AddParameter("password", "pass", ParameterType.GetOrPost);
request.AddParameter("scope", "scope1", ParameterType.GetOrPost);
request.AddParameter("client_id", "api", ParameterType.GetOrPost);
request.AddParameter("client_secret", "rest", ParameterType.GetOrPost);

IRestResponse token = client.Execute(request);
Request Parameters | RestSharp[^]
c# - RestSharp post request - Body with x-www-form-urlencoded values - Stack Overflow[^]
 
Share this answer
 
Comments
Member 14779968 12-May-20 22:47pm    
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900