cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
Want to learn some quick and useful tips to make your day easier? Check out how Calvin uses Replay to get feedback from other teams at Dropbox here.

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

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

Re: Python - Automatic Refresh_token Using oauth-2.0 with offlineaccess

Python - Automatic Refresh_token Using oauth-2.0 with offlineaccess

mauro991
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')

target='/DVR/DVR/'

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"

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

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

            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)
        filesList.extend(files.entries)
        print(len(files.entries))

        while(files.has_more == True) :
            files = dbx.files_list_folder_continue(files.cursor)
            filesList.extend(files.entries)
            print(len(files.entries))

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

            else :
                create_links(target+'/'+file.name, 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:
    if entry.name.endswith(".pdf"):
        # note: this simple implementation only works for files in the root of the folder
        res = dbx.sharing_get_shared_links(
           target + entry.name)
          
        # 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.

mauro991
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?

Thanks

Mauro

Здравко
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.

Greg-DB
Dropbox Staff

[Cross-linking for reference: https://stackoverflow.com/questions/74534382/dropbox-automatic-refresh-token-using-oauth-2-0-with-of... ]

 

@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?