Reputation: 1349
I have the below sample code that attempts to access files on my personal Google Drive account. The earlier version had an annoying problem, namely that Google required manual enabling of it every time it ran, via opening a link in the browser. This is why I modified the code by including Oauth2 and believed it would solve this problem for good. However today, I again found the following console message:
File "c:\...\site-packages\oauth2client\client.py", line 819, in _do_refresh_request
raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Token has been expired or revoked.
I believed that the purpose of the if not credentials
condition in the code below was specifically to renew the credentials automatically based on the client_secrets
file and thus to prevent such manual enabling.
Full code is as follows:
from googleapiclient.discovery import build
from oauth2client import client, tools
from oauth2client.file import Storage
api_client_secret = r"C:\...\client_secret_0123456789-abc123def456ghi789.apps.googleusercontent.com.json"
credential_file_path = r"C:\...\credential_sample.json"
class GoogleDriveAccess:
def __init__(self):
self.service = self.get_authenticated_service(api_client_secret, credential_file_path, 'drive', 'v3', ['https://www.googleapis.com/auth/drive'])
def get_authenticated_service(self, client_secret_file_path, credential_file_path, api_name, api_version, scopes):
store = Storage(credential_file_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(client_secret_file_path, scopes)
credentials = tools.run_flow(flow, store)
return build(api_name, api_version, credentials=credentials)
if __name__ == '__main__':
GoogleDriveAccess()
What am I missing here? How could I ensure that Google doesn't automaically revoke my access right on my own Google account?
Upvotes: 3
Views: 3130
Reputation: 117261
Applications that are in the testing phase have their refresh tokens expired after seven days.
A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testing" is issued a refresh token expiring in 7 days.
Set your app into production and it wont expire
Or consider switching to a service account.
from google.oauth2 import service_account
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
Upvotes: 5