Ever needed to let your GCP code act like it is someone specific on the domain? This is a situation that pops up much more these days in my line of work. Need to put something in a specific calendar, need to move that file to a specific Google Drive… The list goes on and on.
So the question is can this be done and the answer is YES. With delegated credentials this is possible. How much extra work? The good news is that it is one extra click and one extra line of code. Lets have a look how this works.
You will need a service account to make this work. So lets have a look at the steps. On the Google Cloud Console got to “IAM & admin” -> “Service Accounts”
Then make sure to create an account with the “Enable G Suite Domain-wide Delegation” option ticked:
Remember to give the service account API access on the Admin panel of the domain. ( I assume that you know how to do this. If not, just Google it there are many help pages on that)
So from here lets have a look at the code ( in Python today ):
scopes = 'https://www.googleapis.com/auth/admin.directory.user.readonly' credentials = ServiceAccountCredentials.from_json_keyfile_name('./serviceAccountKey.json', scopes) delegated_credentials = credentials.create_delegated('firstname.lastname@example.org') http_auth = delegated_credentials.authorize(httplib2.Http()) directoryService = discovery.build('admin', 'directory_v1', http=http_auth)
First we set up the scopes for the application. Secondly we use the service account credentials (JSON key file) to create the credentials object. Then the next line is where the magic happens.
We use the create_delegated function to specify the user we want to “emulate” or delegate to be. After the http_auth we build the service and access it AS the user specified.
So if you need to FAKE it, thats how do it 😉