Search code examples
c#microsoft-graph-apirestsharp

Refresh token with restsharp


In my Console App I want to refresh a token because token experis after an hour, I am triyng to implement Refreshing a Token section, my code like:

 var client = new RestClient("https://login.microsoftonline.com/common/oauth2/v2.0/token");
 var request = new RestRequest(Method.POST);
 request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
 request.AddParameter("grant_type", "refresh_token");
 request.AddParameter("refresh_token", [My_Token]);
 request.AddParameter("client_id", [My_ClientId]);
 request.AddParameter("client_secret", [My_ClientSecret]);
 request.AddParameter("scope", "offline_access");
 request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
 IRestResponse response = client.Execute(request);
 var content2 = response.Content;

but I'm getting the response:

{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'refresh_token'.\r\nTrace ID: 56e56b4a-92b3-445a-9fcf-972b7a481300\r\nCorrelation ID: 5cb2b84b-f128-4d4f-888c-6c9a3be1d70b\r\nTimestamp: 2019-05-16 13:01:57Z","error_codes":[900144],"timestamp":"2019-05-16 13:01:57Z","trace_id":"56e56b4a-92b3-445a-9fcf-972b7a481300","correlation_id":"5cb2b84b-f128-4d4f-888c-6c9a3be1d70b"}


Solution

  • RestSharp is serializing body in JSON or XML by default. You need GetOrPost to fix that https://github.com/restsharp/RestSharp/wiki/ParameterTypes-for-RestRequest#getorpost

     request.AddParameter("grant_type", "refresh_token", ParameterType.GetOrPost);
     request.AddParameter("refresh_token", [My_Token], ParameterType.GetOrPost);
     request.AddParameter("client_id", [My_ClientId], ParameterType.GetOrPost);
     request.AddParameter("client_secret", [My_ClientSecret], ParameterType.GetOrPost);
     request.AddParameter("scope", "offline_access", ParameterType.GetOrPost);
     request.AddParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob", ParameterType.GetOrPost);