Search code examples
c#curlhttpclient

Converting curl to HtttClient request


Im trying to do this curl request (from API documentation) in HttpClient: Please not that the code below is just copied from their documentation and does not contain any of my information.

POST /oauth/token (get access token)

   $ curl -v -X POST https://api.tink.com/api/v1/oauth/token \
   -d 'code=1a513b99126ade1e7718135019fd119a' \
   -d 'client_id=YOUR_CLIENT_ID' \
   -d 'client_secret=YOUR_CLIENT_SECRET' \
   -d 'grant_type=authorization_code'

   {
       "access_token": "78b0525677c7414e8b202c48be57f3da",
       "token_type": "bearer",
       "expires_in": 7200,
       "refresh_token": "33f10ce3cb1941b8a274af53da03f361",
       "scope": "accounts:read,statistics:read,transactions:read,user:read"
   }

I've tried to make a post request to the oauth/token endpoint both with all the information requested as header (with an empty body) and as a json document (with and without the headers). When I only have the information in the headers I get a 401 back, but I've verified that all the data is correct. All other ways that I've tried has generated a 400.

As far as I can understand the json below the curl is the response, but Im not accustomed at all to curl.


Solution

  • There's a handy site here: https://curl.olsh.me/

    I wouldn't recommend sending secrets over the web, so be sure to anonymise the values first and translate them back after.

    So for the command you've pasted you'd get:

    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.tink.com/api/v1/oauth/token"))
        {
            var contentList = new List<string>();
            contentList.Add("code=1a513b99126ade1e7718135019fd119a");
            contentList.Add("client_id=YOUR_CLIENT_ID");
            contentList.Add("client_secret=YOUR_CLIENT_SECRET");
            contentList.Add("grant_type=authorization_code");
            request.Content = new StringContent(string.Join("&", contentList));
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 
    
            var response = await httpClient.SendAsync(request);
        }
    }
    

    The 401 headers you are getting back may be due to passing in the wrong id and secret, I presume there is a way for you to get test credentials.