Showing results for 
Show  only  | Search instead for 
Did you mean: 
Whether you want to work on being more organized, your productivity or you want to use AI to make your life easier, we’ve got something for you right here.

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

Showing results for 
Show  only  | Search instead for 
Did you mean: 

Python - Automatic Refresh_token Using oauth-2.0 with offlineaccess

Python - Automatic Refresh_token Using oauth-2.0 with offlineaccess

Explorer | Level 3

OK I now: the automatic token refreshing is not a new topic. 

This is the use case that generate my problem: let's say that we want extract data from Dropbox. Below you can find the code: for the first time works perfectly: in fact 1) the user goes to the generated link; 2) after allow the app coping and pasting the authorization code in the input box.

The problem arise when some hours after the user wants to do the same operation. How to avoid or by-pass the newly generation of authorization code and go straight to the operation?

As you can see in the code in a short period is possible reinject the auth code inside the code (commented in the code). But after 1 hour or more this is not loger possible.

Any help is welcome.



#!/usr/bin/env python3

import dropbox
from dropbox import DropboxOAuth2FlowNoRedirect

Populate your app key in order to run this locally
APP_KEY = ""

auth_flow = DropboxOAuth2FlowNoRedirect(APP_KEY, use_pkce=True, token_access_type='offline')


authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
# auth_code="3NIcPps_UxAAAAAAAAAEin1sp5jUjrErQ6787_RUbJU"

    oauth_result = auth_flow.finish(auth_code)
except Exception as e:
    print('Error: %s' % (e,))

with dropbox.Dropbox(oauth2_refresh_token=oauth_result.refresh_token, app_key=APP_KEY) as dbx:
    print("Successfully set up client!")
    for entry in dbx.files_list_folder(target).entries:
    def dropbox_list_files(path):
            files = dbx.files_list_folder(path).entries
            files_list = []
            for file in files:
                if isinstance(file, dropbox.files.FileMetadata):
                    metadata = {
                        'path_display': file.path_display,
                        'client_modified': file.client_modified,
                        'server_modified': file.server_modified

            df = pd.DataFrame.from_records(files_list)
            return df.sort_values(by='server_modified', ascending=False)

        except Exception as e:
            print('Error getting list of files from Dropbox: ' + str(e))

    # function to get the list of files in a folder
    def create_links(target, csvfile):
        filesList = []
        print("creating links for folder " + target)
        files = dbx.files_list_folder('/'+target)

        while(files.has_more == True) :
            files = dbx.files_list_folder_continue(files.cursor)

        for file in filesList :
            if (isinstance(file, dropbox.files.FileMetadata)) :
                filename = + ',' + file.path_display + ',' + str(file.size) + ','
                link_data = dbx.sharing_create_shared_link(file.path_lower)
                filename += link_data.url + '\n'

            else :
                create_links(target+'/', csvfile)

    # create links for all files in the folder belgeler 
    create_links(target, open('links.csv', 'w', encoding='utf-8'))

listing = dbx.files_list_folder(target)
# todo: add implementation for files_list_folder_continue

for entry in listing.entries:
        # note: this simple implementation only works for files in the root of the folder
        res = dbx.sharing_get_shared_links(
           target +
        # f.write(res.content)
        print('\r', res)




4 Replies 4

Legendary | Level 20

Hi @mauro991,

The code you are talking about is for one time use. 🙂 This code is used as a confirmation when refresh token (and others) are going requested. Short after that it's no more valid. You need to keep the received refresh token and reuse it instead of the confirmation code. 😉 Refresh token doesn't expire automatically, but you don't even try to keep it somehow. Why are you requesting refresh token (offline access) while you don't use it actually? 🤷

 Hope this helps.

Explorer | Level 3

Thanks for your answer but I can't solve the problem. May be that I am a bit confused, but according this official post I read "If your app needs to be able to operate long-term without the user present" read how to use “offline” access.

In any case can show me a code example where I can receive refresh token and reuse it instead using confirmation code?



Legendary | Level 20

Hi @mauro991,

Yes, exactly, the reffered post is correct. One of my posts together with the interest to the matter provoked 'official post'. As result of setting "offline" mode, you are receiving refresh token and... instead using it as such (long lived), you are using it as a short lived one! This is your issue. There is no any restrictions how to keep it. It's your design decision.

Hope this sheds some light.

Dropbox Staff

[Cross-linking for reference: ]


@mauro991 Здравко is correct; refresh tokens are long-lived, so you should re-use it. I see in your code you are already requesting offline access and getting back a refresh token. You should store and re-use that resulting refresh token for the user instead of having them process the authorization flow again each time. The dropbox.Dropbox client will handle the refresh process using the supplied refresh token automatically.

Need more support?
Who's talking

Top contributors to this post

  • User avatar
    Greg-DB Dropbox Staff
  • User avatar
    Здравко Legendary | Level 20
  • User avatar
    mauro991 Explorer | Level 3
What do Dropbox user levels mean?