Here is all you need to do to get the refresh token, code snippets are in C#
Step 1: Visit the following URL and finish the steps. in the final step, you should see the Access Code Generated
printed on the screen, copy the code.
https://www.dropbox.com/oauth2/authorize?client_id=YOUR_APP_KEY&response_type=code&token_access_type=offline
Step 2: Get the refresh token using the following code: (NOTE: you'll only need to do it once)
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.dropbox.com/oauth2/token"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("YOUR_APP_KEY:YOUR_APP_SECRET"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var contentList = new List<string>();
contentList.Add("code=ACCESS_CODE_FROM_STEP_1");
contentList.Add("grant_type=authorization_code");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
// process the response
}
}
The response should be something like this:
{
"uid": "XXXXXXXX",
"access_token": "XXXXXXXX",
"expires_in": 14400,
"token_type": "bearer",
"scope": "files.content.read files.content.write",
"refresh_token": "XXXXXXXX",
"account_id": "dbid:XXXXXXXX"
}
You're looking for the refresh_token
. you should securely store it
Step 3: Anytime you need a new access token, run the following code:
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), $"https://api.dropbox.com/oauth2/token"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("YOUR_APP_KEY:YOUR_APP_SECRET"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var contentList = new List<string>();
contentList.Add("refresh_token=REFRESH_TOEKN");
contentList.Add("grant_type=refresh_token");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var res = httpClient.SendAsync(request).Result;
// process the response
}
}
The response should be something like this:
{
"access_token": "XXXXXXXX",
"token_type": "bearer",
"expires_in": 14400
}
You're looking for the access_token
. and also pay attention to expires_in
value, you can and probably should store the access_token
in some sort of memory cache in order to prevent requesting a new token on every API call.
Here is the curl
for getting a new refresh token.
curl https://api.dropbox.com/oauth2/token -d grant_type=refresh_token -d refresh_token=<REFRESH_TOKEN> -u <APP_KEY>:<APP_SECRET>