Search code examples
phpoauthoauth-2.0google-oauthyoutube-data-api

How to get access token from service account


I am new to google oauth and openid connect,lets say i need service account where users store videos in my youtube channel,i created service as given in docs.but i dont know how to get access token lets say my code like this

    $param = $this->getParameter('kernel.root_dir').'/xxxx.json';
    $client = new \Google_Client();
    $client->setClientId('xxxxxxxx');
    $client->setScopes('https://www.googleapis.com/auth/youtube');
    $client->setRedirectUri('http://localhost:8000/youtube/1/token');
    putenv('GOOGLE_APPLICATION_CREDENTIALS='.$param.'');
    $authurl = $client->createAuthUrl();
    $youtube = new \Google_Service_YouTube($client);
    file_get_contents($authurl);

when i run file_get_contents($authurl) am getting 401 error, what mistake i made here ?


Solution

  • You may be confused on a few terms. Oauth2 prompts a user for authentication asking the user may I access your YouTube data. The developer is given a refresh token which they can use to retrieve a new access token and access the data on the users YouTube channel.

    Service accounts are preauthorized. I could take a service account email address and grant it permission to access a folder on my Google drive account it could then read and write to that folder.

    The YouTube API does not support Service accounts.

    For YouTube you will need to authenticate your code once yourself save the refresh token then add that refresh token to your code. Then when another user wishes to upload a Video to your account you use the refresh token to get an access token and upload the file.

    There is a good question here with how to use a refresh token with the php client library How to refresh token with Google API client?

    $client->refreshToken($refreshToken);
    $newtoken=$client->getAccessToken();