BlogSoftware

How to get long lived access (refresh) tokens for Dropbox developer apps

Written by Codemzy on June 13th, 2022

When you generate an access token for the Dropbox API, it's usually short-lived and expires in 4 hours (or less for other users). Here's how to get a refresh token so that access is long-lived and doesn't expire.

I recently stepped into the world of a Dropbox developer and created an app in the app console. It was for a Dropbox CMS, where I could grab some files from a Dropbox app folder and include them in a static website.

I won't go into the details as I wrote about it in another blog post, but I will say that it took me a while to get my head around sharing apps from the Dropbox app console with other users and getting access tokens that do not expire.

Hopefully, writing about my findings here will save you some time if you run into similar issues.

I'll cover:

  • How to create a Dropbox developer app
  • How to generate an access token
  • How to share a Dropbox developer app
  • How to get a long-lived access token (API)
  • How to get a refresh token (manually)
  • How to wire it all up (in JavaScript - NodeJS)

If you want a quick and easy way to get a refresh token, in the how can I get a refresh token (manually) section, you'll be set up with your refresh token in less than 2 minutes!

How do I create a Dropbox developer app?

For the rest of this post, you'll need to have a Dropbox developer app set up. If you don't have one already, you can create one from the Dropbox app console.

Log in and click the Create app button.

create Dropbox app screen

You can find some more information about creating a Dropbox developer app in my Dropbox as a headless CMS post.

I've created an app with App folder permissions, for access to a single app folder (that will be found when a user connects in their Dropbox account under Apps > Your App Name. You can also choose Full Dropbox if you need API access to a user's full Dropbox account (e.g. for accessing a shared folder).

Click the Create app button, and your app is ready!

Make sure you set any permissions you need to in the permissions tab.

How do I generate an access token?

Now you have created your Dropbox app, how do you use it? Because at the moment, no one is connected, not even your own account. Luckily, linking it to your own Dropbox account is easy enough.

In the Generated access token section of the settings tab click the Generate button.

dropbox generate access token

But you will probably notice that the token starts with sl. That token will last for 4 hours, before expiring. It's enough to test your app, but not for long-term use.

We'll cover how to create a long-lived access token (with a refresh token) shortly.

How can I share a Dropbox developer app?

So you've linked your account up by generating an access token. But what about if you want other users to use your Dropbox app?

This is one of the first gotcha's I came up against.

If you want other users to have access, you can click the Enable additional users button under the "Development users" section. Now up to 500 people can have access!

If you're like me, you'll click this button and think, "great, how can they access it?".

You can't just share a Dropbox app with other users like you would a Dropbox folder. It's not a shared folder.

To explain the difference, an app with App folder permission gets a shared folder between your app and the user. If your app has 10 users, it will have 10 shared folders, one in each user's account.

An app with Full Dropbox permissions gets access to the Dropbox account of each user that connects (to whatever permission level you set up in the permissions tab).

Because of this, the way Dropbox intends you to share the app is through their API. As in, you'll build a website or some other service, and when a user activates their account, you'll call the Dropbox API so that the user can authorise access.

And that makes sense because they are connecting with the app, not with you.

But if you're just testing things out (like I was), and need a quick way to authorise your app from a Dropbox account that isn't your own, you can share this link to do it.

https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code

Replace <APP_KEY> with your Dropbox app key (from the settings tab).

After confirming they want to give your app access, they will get an access code.

dropbox access code generated

And they can also find the app folder (if you created an app with App folder and not Full Dropbox permissions) in their Dropbox account under Apps > Your App Name.

But just like the token you created for your account, it will be short-lived.

How can I get a long-lived access token for Dropbox?

Here's how you do it through the API, but I'll share a handy manual workaround in the next section.

There's no easy way to get a long-lived access token through the Dropbox App Console. This is designed for testing out your app before you go to production, so for security, the tokens are short-lived.

And maybe short-term access tokens are all you need. If you only access Dropbox based on a user action, you can request a new access token through the API each time (with the user's approval). For example, each time a user logs in to your website or app.

But what if your app needs to call the API when a user isn't active. For example, I created a Dropbox CMS that needs to access an app folder every time a static website is built. The user won't be around for that. And if it was my account, I don't want to have to keep generating tokens when I need them.

If you want to create a permanent or long-lived access token you are supposed to do it through the API.

And it works by getting a refresh token, that you can use anytime to get new short-lived access tokens when you need them.

Here's how you would get (and set) a refresh token with JavaScript.

npm install --save dropbox

Here's a snippet below where we get an access token from an access code and get the refresh token from the result. You can get the full example from dropbox-sdk-js](https://github.com/dropbox/dropbox-sdk-js/blob/b5631e4b5b0e9eb6d3297e1ee57ad29a63d49898/examples/javascript/PKCE-backend/code_flow_example.js#L38).

 dbx.auth.getAccessTokenFromCode(redirectUri, code)
     .then((token) => {
     console.log(`Token Result:${JSON.stringify(token)}`);
     dbx.auth.setRefreshToken(token.result.refresh_token);
         //...

If you're using a different programming language, here are the SDKs available for Dropbox, (scroll down to the SDK section).

Once you have that refresh token saved, you can use it, again and again, to get new access tokens when you need them.

Here's how you'd set it up in your code.

const fs = require('fs');
const { Dropbox } = require('dropbox');
const dbx = new Dropbox({ 
  clientId: '<APP_KEY>',
  clientSecret: process.env.DBX_CLIENT_SECRET,
  refreshToken: process.env.DBX_REFRESH_TOKEN
});

The clientId is your app key, and the clientSecret is your app secret. You can get both of these from your app, under the settings tab. The refresh token is the token you get from whoever is giving your app access to their Dropbox account (this could be your account or someone else's).

If you haven't been able to get the refresh token, and don't want to mess about with the Dropbox SDK or write a bunch of code to do it - I have a workaround!

Let's be anti-developers. We'll go manual and un-automate it!

How can I get a refresh token (manually)

So we've covered how a refresh token is needed to create a long-lived way to access the Dropbox API. And how you can do that through the various Dropbox SDK options for whatever programming language you use.

But to be honest (and I'm not ashamed to admit this), I did it manually.

Why? Because I only needed access to one account for my app. And I wasn't about to write a bunch of code to automate a process that would be just as quick to do manually.

Get a new access code

https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code

This is the same link from the How can I share a Dropbox developer app? section, but get a fresh access code because they expire quickly.

Get the refresh token

You can send a post request with the access code to get a refresh token.

curl --location --request POST 'https://api.dropboxapi.com/oauth2/token' \
-u '<APP_KEY>:<APP_SECRET>'
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code=<ACCESS_CODE>' \
--data-urlencode 'grant_type=authorization_code'

Or here is how you can do it with the JavaScript Fetch API.

var myHeaders = new Headers({
  "Authorization": `Basic ${base64.encode("<APP_KEY>:<APP_SECRET>")}`,
  "Content-Type": "application/x-www-form-urlencoded"
});

var urlencoded = new URLSearchParams({
    "code": "<ACCESS_CODE>",
    "grant_type": "authorization_code"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow'
};

fetch("https://api.dropboxapi.com/oauth2/token", requestOptions)
  .then(response => console.log("refresh_token", response.json().refresh_token))
  .then(response => console.log(response.text()))
  .catch(error => console.log('error', error));

You could also use something like Postman to make the request. Here are some more detailed instructions for what the Postman request would look like.

Now you have a refresh token, you can wire it up in your code.

const fs = require('fs');
const { Dropbox } = require('dropbox');
const dbx = new Dropbox({ 
  clientId: '<APP_KEY>',
  clientSecret: process.env.DBX_CLIENT_SECRET,
  refreshToken: process.env.DBX_REFRESH_TOKEN
});