Search code examples
phpgoogle-apigoogle-oauthgoogle-api-php-clientservice-accounts

Do we need to refresh tokens when using a google service account


I have a google service account and I do the authorization as follows

$client = new Google_Client();
$client->setAuthConfig('service_account.json');
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/admin.directory.user');
$email="admin@xxxxx.com";
$client->setSubject($email);

I then create a service object as follows

$dir = new Google_Service_Directory($client)

Now, I've been able to operate on this object like create new user etc. without any issue. I am wondering if I will need to refresh a token at some stage. Can you help me figure out if this is necessary and if so, how to check this condition and get a new token?


Solution

  • Service accounts are preauthorized. Your authentication is linked back to the .p12 file or some of the private key within the json file. Those keys are in a sense Refresh tokens if you like. As long as you have those keys you will be able to get access to Google.

    As far as OAuth2 goes, when a Google user consents to your application accessing their data you are given a refresh token which will allow you to access their data.

    There is a difference but in a sense refresh token and the private_key preform the same action. They allow you to access data that you have been granted permission to access. In the case of a service account, it's preauthorized. In the case of OAuth2, it's granted by a user.

    As you can see, you don't need to worry about refresh tokens or access tokens really with the code you are using. Everything should be handled for you by the client library.