Skip to content

Instantly share code, notes, and snippets.

@veuncent
Last active July 12, 2023 18:53
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save veuncent/e0b831ab41d598961d2656c7fc5cc0f9 to your computer and use it in GitHub Desktop.
Save veuncent/e0b831ab41d598961d2656c7fc5cc0f9 to your computer and use it in GitHub Desktop.
Authentication for Google / YouTube Analytics using a Brand Account

Google / YouTube Authentication using a Brand Account

Below describes the only way I was able to get (programmatic) access to the YouTube Analytics API on behalf of our Brand Account. Google documentation is convoluted, to say the least, so if you know a more straightforward way, please do share.

Getting a Client ID and Refresh Token

  1. Create a Project in the Developers Console - https://console.developers.google.com/
  2. Go to the Library tab and enable desired APIs (e.g. YouTube Analytics)
  3. Go to OAuth consent screen and make project external. Select Test mode
  4. Go to Credentials and create OAtuh Client ID credential: Application type = web; redirect uri = https://developers.google.com/oauthplayground
  5. Go to https://developers.google.com/oauthplayground
  6. Select gear icon -> Access type = Offline, Force prompt = Select Account Screen, Use your own OAuth credentials = checked --> enter client id and client secret from step 4
  7. Click Select & authorize API's and select the desired APIs (e.g. https://www.googleapis.com/auth/youtube.readonly , https://www.googleapis.com/auth/youtubepartner , https://www.googleapis.com/auth/yt-analytics-monetary.readonly and https://www.googleapis.com/auth/yt-analytics.readonly
  8. Click 'Authorize APIs'
  9. In the consent screen, first select your Google account, then in the next screen select your brand account
  10. Back in the OAuth Playground, you received an Authorization Code. Click Exchange authorization code for tokens
  11. Copy the Refresh token
  12. Go back to your project in the Developers Console and change the User type to internal by clicking the Make internal button
  13. Download your Client ID json from the Developers Console: Credentials -> OAuth 2.0 Client IDs table -> Click the download icon next to your Client Id (in the far right of that row)

Usage in .NET

public async Task<QueryResponse> GetResponse() 
{
    var credential = GetUserCredential("<YOUR_ClientIdJson>", "<YOUR_RefreshToken>");

    QueryResponse response;

    using (var youTubeAnalyticsService = new YouTubeAnalyticsService(new BaseClientService.Initializer
    {
        HttpClientInitializer = credential,
        ApplicationName = Assembly.GetExecutingAssembly().GetName().Name,
    }))
    {
        var request = GetRequest(youTubeAnalyticsService);
        response = await request.ExecuteAsync();
    }
}

private UserCredential GetUserCredential(string clientIdJson, string refreshToken)
{
    var stream = GetClientIdStream(clientIdJson);
    var token = new TokenResponse { RefreshToken = refreshToken };

    return new UserCredential(
        new GoogleAuthorizationCodeFlow(
            new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = GoogleClientSecrets.Load(stream).Secrets
            }), 
        "user",
        token
        );
}

private static MemoryStream GetClientIdStream(string clientIdJson)
{
    var stream = new MemoryStream();
    var writer = new StreamWriter(stream);
    writer.Write(clientIdJson);
    writer.Flush();
    stream.Position = 0;
    return stream;
}
@yorkshire-pudding
Copy link

Is there a step missing between 11 and 13? Where do I paste the Refresh token?

@veuncent
Copy link
Author

@yorkshire-pudding You can use the refresh token in your code to create a UserCredential, like in line 3 in the example (<YOUR_RefreshToken>)

@bmiselis
Copy link

Doesn't the refresh token generated in such way expire after 7 days? source

@JohannaShiri
Copy link

Thanks for the steps!!
In my case, after choosing my brand account I got "Error 403: Forbidden".
Apparently, I had to go back to Google Cloud and add myself as a test user.

Here's a StackOverflow question, related to this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment