问题
I am connecting to a service account using a service account credential.
I'm trying to scale this up to be used for multiple users within the same company. All users will have Google accounts managed by this company, and I will have a gsuite service account for the entire company. How can I upload a file to users personal Google Drive based on an email address using a gsuite service account?
回答1:
You want to use ServiceAccountCredential
, with a User
property set to the appropriate user.
Assuming you're loading the credentials using GoogleCredential
, this isn't too hard. For example:
GoogleCredential credential = Google.GetApplicationDefault()
.CreateScoped(...)
.CreateWithUser("foo@bar.com");
If you wanted to use the same original credentials for many different users, you could keep the result of CreateScoped(...)
around, and just call CreateWithUser
to create a new user-specific credential for each operation.
回答2:
Using Oauth2 you are going to have to have each of the users authentication your application. This will give you access to their drive account directly. Now you say you have a master user. You could just request that these other users share a folder on their Google drive account with the master user then it will have access. Note you can't share the root directory.
You might want to consider using a service account instead of oauth2 this the users will then have to grant the service account access to their drive account.
Now if this is a gsuite users all of this can be automatically done useing domain wide delegation of the service account.
回答3:
Here in my work we have the same scenario as you, and to be able to achive this type of integration we created a service account with wide domain delegation enabled for this account.
This way we can use the service account to access users data on their behalf.
But for that, when creating the service account credential, you must impersonate the service account credential passing the user email, this way you'll be able to access user data on their behalf using the service account.
Since you're using C#, I've created a small library that create service account credentials for any type of google api services and for both JSON or P12 credentials.
https://github.com/drodriguesaar/GoogleApiServiceFactory
来源:https://stackoverflow.com/questions/49615473/using-service-user-to-upload-files-to-google-drive-by-email-address