ホーム 暮らし [Go Language] A Story of Getting Stuck with Google Calendar API OAuth Integration (A 2021 Memo)

[Go Language] A Story of Getting Stuck with Google Calendar API OAuth Integration (A 2021 Memo)

篠原 沙世 篠原 沙世 • 更新: • 公開: • 読了約 34 分
目次

This article is a memo summarizing the many pitfalls I encountered when trying to integrate the Google Calendar API into a web application around 2021. While the GCP UI and other elements may have changed since then, the fundamental "stumbling blocks" of OAuth integration remain the same, so I hope this serves as a reference for those who will be implementing it in the future.

1. The Trap of Official Documentation (Desktop instead of Web App?)

n9ecc75808cc4

I started by following the official documentation (Google Workspace for Developers).

To use the API, you need to enable the Calendar API in GCP (Google Cloud Platform) and download the credentials.json file.

I navigated from the menu to "APIs & Services" > "Credentials" to create an OAuth 2.0 Client ID, but that was where I first got confused.

The official documentation didn't have a "Web Application" option, and only provided instructions for a "Desktop Client."

Wondering "Why, when I want to build a web app?", I went ahead and selected Desktop Client and downloaded the JSON.

(As I will mention later, to eventually run it as a web app, I had to go back and correctly select "Web Application" here. This is a point where you will get lost if you follow the official documentation exactly.)

2. The Mystery of the Sample Code (Doesn't work in Go, but works in PHP?)

Next, I tried the Go language quickstart sample using the downloaded JSON.

However, no matter how many times I tried, it wouldn't work and kept returning the following error.

Plaintext

Unable to parse client secret file to config: oauth2/google: no credentials found

I spent an entire day Googling the error message, wondering if the scope was insufficient. I ended up wasting more than half a day suspecting that the JSON file itself was wrong...

As a test, I tried running a PHP sample code I found on Qiita... and to my surprise, it successfully retrieved the calendar events (schedule) without any issues! I held my head in my hands, wondering, "Why does it fail in Go when using the same credentials?"

Cause: The sample was referencing the wrong thing

When I carefully traced the Go sample code, I discovered that it was actually leading me to the Gmail API sample code instead of the Calendar API. No wonder it didn't work. I had to find the correct Calendar sample on GitHub and try again.

3. The Authentication Code Trap (Malformed auth code)

When I ran the correct Go sample, the following message was displayed in the console.

Plaintext

Go to the following link in your browser then type the authorization code: 
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=...

As instructed, I accessed the URL in my browser, went through the consent screen with my Google account, and was redirected to http://localhost/. The specification required me to copy the code= argument attached to that URL and paste it into the console.

When I finally pasted it and pressed Enter, I got this error instead.

JSON

400 Bad Request
Response: 
 "error": "invalid_grant",
 "error_description": "Malformed auth code."

exit status 1
Solution: URL decoding is required

After searching on Google, the cause was that I was pasting the URL-encoded string as it was.

By first URL-decoding the copied code parameter value before pasting it into the console, I was able to proceed to the next step without any issues.

4. The Refresh Token Disappearance Incident

While repeating the OAuth tests several times, I noticed something terrifying.

“Wait? The refresh token isn't coming back…?”

The refresh token is necessary to reissue an access token once it expires. It was definitely there before, but no matter how many times I tested, I couldn't get it anymore.

Is it because it's a desktop app? Is it a web app? Is it a grant_type issue? Are there settings other than access_type=offline? I looked into various things.

Solution: Refresh tokens are only granted upon the 'initial consent'

Actually, Google's OAuth has a somewhat tricky specification where 'a refresh token is only granted upon the initial consent (initial login), and only an access token is returned thereafter'.

Therefore, because I was trying the integration many times for testing, I was no longer able to acquire the token.

Ultimately, I was able to successfully re-acquire the refresh token by revoking the app's integration (access rights) on the GCP side and recreating the authentication credentials.

5. Finally, schedule acquisition success! & The true identity of Go's unique syntax

After many twists and turns, I finally succeeded in acquiring the schedule information.

If you want to specify a particular calendar, all you had to do was enter the calendar ID in the "primary" part of the code below.

Go

srv.Events.List("primary").ShowDeleted(false).
 SingleEvents(true).TimeMin(t).MaxResults(10).OrderBy("startTime").Do()

By the way, when I was just starting out with the Go language, I was very confused by this "way of writing where functions are strung together with dots (.)".

I understood intuitively that "it must be passing the return value from left to right," but in programming terms, this is a style called Method Chaining or Builder Pattern.

It is a beautiful design technique often used when building up request conditions (options) for an API step by step.

6. Final step: Integration into a WEB application

Since the sample worked without issues, it is finally time to integrate it into my own WEB application.

To summarize, the flow is as follows.

  1. Pass parameters with CalendarAuth1 and redirect to Google's consent screen

  2. User gives consent

  3. Redirect back to CalendarAuth2 (my app's callback URL) with a code parameter

To build this flow, you need to re-create the credentials as a "Web application" instead of a "Desktop client" on GCP.

[Correct setup procedure for WEB apps]

  1. APIs & Services ➡ Credentials ➡ Create OAuth 2.0 Client ID.

  2. Select "Web application" for the application type. (If you choose Desktop, you cannot set the redirect destination)

  3. "Authorized redirect URIs", set the URL of your own app that you want to return to (e.g., [https://example.com/CalendarAuth2/](https://example.com/CalendarAuth2/)).

  4. Save and download the new JSON to use.

If you manually edit the redirect specification in the downloaded JSON locally and send the request, you will get a "redirect URI is mismatch" error on Google's consent screen. Please make sure to match the settings on the GCP console.

A story about getting lost in a labyrinth of documentation and UI when implementing Google Login (Google Identity) in Go for the first time in 10 years

About 10 years ago, I implemented a Google OAuth login feature in an app.

In my memory from back then, Facebook was the simplest and easiest, followed by Twitter, and Google was overwhelmingly difficult and time-consuming. I remember it being quite complicated because Google had a huge number of APIs and the structure of the documentation was updated frequently, making it easy for discrepancies to arise between the information found via search and the actual specifications and documentation.

10 years later. When I tried implementing a login feature using Google's API for the first time in a while, it had become even more difficult and even more complicated.

Due to version updates, I spent a huge amount of time just trying to figure out which documentation was the correct one.

  • Google Cloud Platform page

  • Google OAuth page

  • Google Identity page

After much trial and error, I discovered that the correct source for this implementation was the "Google Identity Services (GSI)" page. It took me an entire day just to realize this.

1. The first trap: [GSI_LOGGER] errors and confusion with the console UI

As I read through the official documentation (Google Identity), it stated that simply replacing the client-id in the provided HTML sample would display the Google login button.

I immediately created the HTML and displayed it, but although the button itself appeared, the popup that opened when clicked remained blank and did not work.

Checking the browser's developer tools, I found the following error occurring.

Plaintext

[GSI_LOGGER]: The given origin is not allowed for the given client ID.

I would end up stuck for a whole day trying to resolve this error.

Searching for the error message suggested that it was a cross-domain error and that I should allow it, so I adjusted the Nginx config and tried adding the following to the HTML header.

HTML

<meta name="referrer" content="strict-origin-when-cross-origin" />

However, it did not improve at all.

The documentation said to add the authorized domain to the "Authorized JavaScript origins box", but I couldn't find where that input form was in the GCP console. To make matters worse, I thought, "Do I need to activate Google Search Console?" and tried setting that up, but it had no effect...

Just when I thought I was out of options, I realized I had made a major misunderstanding while recreating the credentials.

console.cloud.google.com

> "APIs & Services" > "Credentials" > "Create Credentials" > "OAuth client ID"

There is a dropdown here to select the "Application type," but because the placeholder "Application type" was displayed as the top option, I misunderstood it to be the title of the selection. Furthermore, since I remembered setting it up for a desktop environment when I used the Google Calendar API previously, I assumed that "Web application" would mean something similar to desktop.

Once I corrected this misunderstanding and explicitly selected "Web application"... there it was!

The input field for "Authorized JavaScript origins" that I had been looking for appeared.

When I entered the domain of the sign-in page and the redirect destination there, the popup functioned correctly, and the credential (JWT) data was successfully POSTed to the redirect destination.

2. JWT Parsing and Verification in Go (Security Measures)

Since the CSRF protection data and credentials were POSTed to the redirect destination, the next step is to parse them and extract the user information (sub).

However, I was troubled by the structure of the documentation here as well.

You cannot reach the parsing explanation page unless you follow the small decode link at the edge of the thousands-of-lines-long HTML reference.

Furthermore, even if you look at the official token verification guide, although it is touted as recommended, it only presents code for JS, PHP, Python, etc., and I could not find an official Go sample. Even when searching the same hierarchy as the Google API PHP Client example, there was no sample for Go.

So, I attempted to parse it using the standard JWT library, github.golang.org/golang-jwt/jwt/v4.

However, initially, token.Valid became false, and I stumbled on retrieving the sub. The cause was that Google's JWT is signed with public-key cryptography (RSA), so verification with a general secret key resulted in an error.

To securely verify the signature while retrieving the sub, I eventually realized that the correct approach was to use the official Google Go package, google.golang.org/api/idtoken.

Implementation Code (Go)

Bash

go get google.golang.org/api/idtoken

Go

package main

import (
	"context"
	"fmt"
	"log"

	"google.golang.org/api/idtoken"
)

func verifyGoogleToken(credentialString string, clientID string) (string, error) 
	// Googleの公開鍵(JWKS)を自動取得し、署名・有効期限・Audienceを安全に検証
	payload, err := idtoken.Validate(context.Background(), credentialString, clientID)
	if err != nil 
 return "", fmt.Errorf("トークンの検証に失敗しました: %v", err)
	

	// 安全に確認されたユーザー一意識別子(sub)を取得
	userID := payload.Subject
	return userID, nil

By including this process, I became able to reliably and securely retrieve the sub while rejecting forged tokens.

3. Session Management Design

The sub obtained from Google Identity includes information such as the expiration date, and there is a way of thinking that uses the token itself as a session. However, if you perform external API calls or token verification every time you check a session, it leads to a decrease in response speed and increased processing complexity.

Therefore, I adopted a configuration where authentication is left to Google, while session management within the system is handled by my own database (DB) using the extracted sub as a key. (There is an option to include Redis, but this time I adopted DB management to keep the configuration simple.)

Summary

Despite stumbling around, I was able to successfully build a login feature using Google Identity Services in Go.

My impression is that the difficulty and complexity have increased by about 1.5 times compared to 10 years ago (lol). I was troubled by the scattered documentation and UI traps, but in the end, I was able to utilize the official library to implement a solution that ensures robust security.

I hope this will be helpful for those who are getting stuck in similar places.

Reference links
  • Google Identity Services - Verify the Google ID token

  • OAuth 2.0 Token Expiration


同じカテゴリの記事

篠原 沙世

アニメとゲームの新作情報を担当。制作会社・配信元の公式告知と登壇情報を照合して記事化します。

おすすめの関連記事