I've shared a Google Sheet with my Google Service account email, which looks something like:
This permits my application to access that Google Sheet.
I'd like to be able to share the Google Sheet with a custom email address (e.g. [email protected]) aliased to that ugly autogenerated service account email ([email protected]
).
How could I go about doing this?
edit:
Example of code used for interacting with Google APIs
from google_auth_httplib2 import AuthorizedHttp
from google.oauth2 import service_account
import pygsheets
def _get_gc():
scope = ['https://www.googleapis.com/auth/spreadsheets']
credentials = service_account.Credentials.from_service_account_file(
settings.GOOGLE_SERVICE_AUTH_FILE,
scopes=scope,
)
http = AuthorizedHttp(credentials, http=HTTP)
logger.info('Created GC creds, returning...')
return pygsheets.authorize(custom_credentials=credentials, http=http)
def do_something(url):
gc = _get_gc()
spreadsheet = gc.open_by_url(url)
Unlike regular accounts, service accounts cannot have aliases. Their email address is defined by:
You cannot give it additional aliases.
If you want to avoid sharing the Google Sheets with the autogenerated service account email address, but you want to keep using the service account to interact with the API, your best option would be to share the Sheets with a regular account that has an acceptable email address, and use the service account to impersonate this regular account, when interacting with the API.
One of the most useful things about a service account is that you can grant it the ability to impersonate any user in your domain and access data on behalf of it. This is called domain-wide delegation, and it can be activated for a service account by following these steps:
Important: You need to be an administrator of the G Suite domain in order to delegate domain-wide authority.
At this point, your service account can impersonate any user in the account. To actually impersonate an account, you would just need to specify which account you want to impersonate when building the credentials.
In your specific case, you would need to provide the parameter subject
when calling from_service_account_file
, as you can see on the domain-wide delegation section of this page:
credentials = service_account.Credentials.from_service_account_file(
settings.GOOGLE_SERVICE_AUTH_FILE,
scopes=scope,
subject="[email protected]"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With