GoogleDrive REST API Authentication without intervention - google-drive-api

What i need to do is to authenticate myself into the GoolgeDrive API (I use it in python) to access my drive to do some automatique task.
I would like that my script run alone every hour without any intervention. So what i need is a way to create a credentials object with my login and password.
Is it possible without any redirection and so on?

I think it is not possible to achieve this with user id and password. The way Google Drive implements this is using a refresh token. That means that you authenticate your app one time interactively. This enables you app for one hour. If the refresh token mechanism is properly configured, the app will renew the token every time it needs it subsequently.
Basically the following steps need to be taken
Visit console.developers.google.com
Register a project and obtain Oauth Client IDs
Select as type web server and enter "http://localhost:8080/" as authorized redirect URL
Download the client_secrets.json and store it in the root of your python app
Create a file called "settings.yaml" at the same place with the following content
client_config_backend: settings
client_config:
client_id: YOUR_CLIENT_ID_GOES_HERE
client_secret: YOUR_CLIENT_SECRET_GOES_HERE
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.son
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
- https://www.googleapis.com/auth/drive.install
In your python code you need to do proper authentication and credential saving:
gauth = GoogleAuth()
gauth.settings["get_refresh_token"]=True
gauth.settings["approval_prompt"]="force"
if exists(self.credsFile):
gauth.LoadCredentialsFile(self.credsFile)
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebserverAuth()
gauth.SaveCredentialsFile(self.credsFile)
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
gauth.Authorize()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile(self.credsFile)
self.driveInstance= GoogleDrive(gauth)
Make sure that you pass in self.credsFile as a valid filename
Executing this code should give you a URL at the console. Copy it to a browser, authenticate and give your consent. Google should ask you for two consents, the second is to authenticate for Google Drive - which is actually done by the refresh token.
The redirect url from the initial credential config in the developer console is called once the consent is given. It calls the temporary web server started by your application. This is how the call back is done. (This implies you have to run browser and your app on the same machine for this step - you may copy over all three files to your server)
From now on your app should run forever without requiring user interaction.

Related

Acquire server side API key for my Google account

I am trying to get account credentials for my Google account which can be stored in a command line file. The script expects these 3 parameters to be set.
local client_id = ""
local client_secret = ""
local refresh_token = ""
So I expect I need some kind of OAuth token which will never be invalidated.
Does anyone know how to acquire it?
You get the client id and the client secret from the Google dev console. You get the refresh token by doing a one-time authorization.
All of the steps are detailed in this answer How do I authorise an app (web or installed) without user intervention? (canonical ?)
Be very careful about how you secure the refresh token. It acts like a username/password for your Drive account, so could be used by "bad dudes". It's a good idea to use the most restrictive scope (step 8 in the above list). drive.file is a good choice if your script is uploading. If your script needs to download files, try drive.readonly.

Document List API to Drive SDK and Client Login

We used to have an application connector implementing the Document List Service v3 to upload documents to users account. Now that the service will be discontinued starting as of next Monday and we need to migrate to the Drive API/SDK we have the problem to migrate our current login schema .. we are unable to use the OAuth 2 protocol and we need to authenticate users with their username/password credentials.
DocumentsService myService = new DocumentsService("xxx");
myService.setUserCredentials(username, password);
The reason is that our application scans and processes documents asynchronously from MFD devices (printers) and all processing/storage job is done in a different moment on processing servers, thus the limitation that the processing service cannot ask any consens to the user.
We do the same for other online cloud storage application (e.g. Dropbox) where they allow special 'OAuth 1' schema on request for such 'enterprise' situations.
How can we do this with the new Drive API/SDK? I couldn't find anything about that in the documentation rather than the service account, also looks like not suitable.
What you need to do is request authentication from you user once. The server gives you back a refresh token. Your automated application can then use this refresh token to get a new access token. You only need to ask the user one time for authentication. Then everything can run automated.
A service account wont really work in this instance because its meant for use with an account that you the developer own not a users account

How to prevent suspended Google account to signup

I am integrating ASP.NET application using Google Drive API. For this after authentication we re uploading Files to Google drive. I am using Google client library to Call the APIs.
Everything is working as expected I am able to authenticate user successfully and able to upload the file successfully.
In one scenario when the user Google account is suspended then I am getting refresh token from Google but my upload method is failing and it is not uploading the file to Google drive.
I want to restrict the user on Signup screen itself, when account is suspended.
What parameter do I have to pass to achieve this please suggest?
Unfortunately this info is not easily available. You have two options :
Use the Directory API to see if the user is suspended. This requires additional OAuth permissions to be provided by an admin of the domain.
At login, try and perform a Drive API call to see if you get an error or not. If you get an error (with a couple of retried) and the error message matches the one you had for suspended users, then you can deny access to the user.

Automate the oauth authentication without browser in cron utility

I am trying to upload some documents on Google drive, i want to run a cron script which is executed at mid night every day and the files generated as a result of it should be uploaded on the uses Google drive.
I tried the standalone script, which uploads document on Google drive, but for that i have to every time do allow access via browser.
However my purpose is to run a cron and upload the files, at the time the cron executes there will be no browser access.
Is there any way i can do the authentication process without manual intervention.
any help in this case would be really appreciated.
THanks,
you can authorize your App(script) with Google Drive.
Here, you mentioned you are writing a script which upload docs to your Google Drive.
I suggest you register a app in Google Cloud Console to get client ID and client Secret firstly,
and turn on Drive API for you registered App.
Then use this client ID and Secret to run oauth flow in your script to get an access token and refresh token, the access token's lifespan is about 3600s, and if it's expired, you can also get a new one with the refresh token.
User's interaction(consent) is required only in the first time you request access token.
In this way, your script can work in "a real script way".
Here are some reference:
https://developers.google.com/drive/about-auth
https://developers.google.com/accounts/docs/OAuth2InstalledApp?hl=zh-CN
I am assuming its only one user drive account you are uploading to. Have you considered using a service account fo this? https://developers.google.com/drive/service-accounts
If its not a single user account you are uploading you can just save the refresh token some place and use that to get a new authtoken every night.
Hi i figured the problem,
i was generating refresh token from oauthplayground and was trying to integrate it in the php script....which was invalid......
I then printed the refresh token returned for the first time when a user allows access and used that for future generation of access token and it works like charm. thanks All for help

appNotInstalled when the refresh token is missing?

Lately I've been noticing a strange behavior when trying to access Drive specific actions. The use case is as follows:
the user installs the Chrome Store application
the user launches the application, we get a refresh token for the email and the profile scopes
the user wants to export a document into Google Drive
error message 403: appNotInstalled is returned
If the user goes to Google Drive and opens a file from there using our application, they are redirected to a new authorization dialog that asks for the email, profile, drive scopes. After the user grants access, the initial export also works fine. My assumption is that the initial refresh token that we had was no longer valid, even though exchanging it for an access token worked and the refresh tokens don't expire.
Shouldn't we receive a more descriptive error message in this case that would suggest that we simply have to redirect the user to the authentication dialog instead of the Chrome Store listing?
The issue might be that you are using a different client id/secret than the one you registered for the Drive SDK.
A quick test would be to:
revoke all granted tokens for your application on your test account
visit your application from the New Tab Page, it should redirect you to the authorization page: copy the URL you generated (do not approve).
visit your application from Drive, it should redirect you to the authorization page: copy the URL (do not approve).
Make sure the 2 URLs are identical (they should be), especially look for similarities in the scope and client_id query parameters.