Webアプリケーション向けGoogle OAuth 2.0
認可コードフロー、スコープ、トークン処理を含むWebアプリケーションでのGoogle OAuth 2.0実装のステップバイステップガイド。
Real-World Flows
詳細な説明
Webアプリ向けGoogle OAuth 2.0
GoogleのOAuth 2.0実装は、Google固有のエンドポイントと規約を持つ標準的な認可コードフローに従います。このガイドでは、サーバーサイドWebアプリケーションの完全な実装を説明します。
Google OAuth 2.0エンドポイント
| エンドポイント | URL |
|---|---|
| 認可 | https://accounts.google.com/o/oauth2/v2/auth |
| トークン | https://oauth2.googleapis.com/token |
| ユーザー情報 | https://www.googleapis.com/oauth2/v2/userinfo |
| トークン取り消し | https://oauth2.googleapis.com/revoke |
| ディスカバリドキュメント | https://accounts.google.com/.well-known/openid-configuration |
ステップ1:OAuth認証情報を作成
- Google Cloud Console > APIとサービス > 認証情報に移動
- 「Webアプリケーション」用の「OAuth 2.0クライアントID」を作成
- 承認済みリダイレクトURI(例:
https://yourapp.com/auth/google/callback)を追加 client_idとclient_secretを保存
ステップ2:認可リクエスト
https://accounts.google.com/o/oauth2/v2/auth
?client_id=YOUR_CLIENT_ID
&redirect_uri=https://yourapp.com/auth/google/callback
&response_type=code
&scope=openid%20email%20profile
&state=RANDOM_STATE
&access_type=offline
&prompt=consent
Google固有のパラメータ:
access_type=offline— リフレッシュトークンをリクエストprompt=consent— 同意画面を強制(再認証時のリフレッシュトークン取得に必要)
ステップ3:コールバックの処理
// stateパラメータを検証
// コードをトークンに交換
const response = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
code: authorizationCode,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
}),
});
const { access_token, refresh_token, id_token } = await response.json();
ステップ4:ユーザー情報を取得
const userInfo = await fetch(
"https://www.googleapis.com/oauth2/v2/userinfo",
{ headers: { Authorization: `Bearer ${access_token}` } }
).then(r => r.json());
// userInfo: { id, email, verified_email, name, picture, locale }
一般的なGoogle OAuthスコープ
| スコープ | アクセス |
|---|---|
openid |
OpenID Connect(必須) |
email |
ユーザーのメールアドレス |
profile |
名前、写真、ロケール |
https://www.googleapis.com/auth/drive.readonly |
Google Driveファイルの読み取り |
https://www.googleapis.com/auth/calendar.events |
カレンダーイベントの管理 |
https://www.googleapis.com/auth/gmail.readonly |
Gmailメッセージの読み取り |
ユースケース
ユーザーに「Googleでサインイン」を許可するWebアプリケーション。アプリがGoogleの認可ページにリダイレクトし、コールバックで認可コードを受信し、トークンに交換し、ユーザーのプロフィール情報を取得してアカウントを作成または更新します。