Chrome拡張機能からFirebaseに接続する方法 ― chrome.identity APIによる認証実装
概要
Chrome拡張機能(Manifest V3)からFirebase Authenticationに接続し、Firestoreでデータを同期する方法を解説する。通常のWebアプリで使うsignInWithPopup()はCSP制限で使用できないため、chrome.identity.getAuthToken()を利用する。
課題
Chrome拡張機能からFirebaseを利用する際、通常のWebアプリと同じアプローチでは動作しない。
// 通常のWebアプリ(動作する)
const provider = new firebase.auth.GoogleAuthProvider();
await firebase.auth().signInWithPopup(provider);
// Chrome拡張機能(動作しない)
// → CSP違反: Refused to load the script because it violates
// the Content Security Policy directive
| 制約 | 理由 |
|---|---|
signInWithPopup()が使えない | CSPが外部サイトへのポップアップを制限 |
| CDN経由のSDK読み込みが使えない | CSPが外部スクリプトの読み込みを制限 |
| 拡張機能IDが読み込みごとに変わる | OAuthリダイレクトURIの固定が困難 |
解決策
アーキテクチャ
┌─────────────────┐ ┌─────────────────┐
│ Web版 (PWA) │────▶│ Firebase │
└─────────────────┘ │ Firestore │
│ │
┌─────────────────┐ │ (同じデータ) │
│ Chrome拡張 │────▶│ │
└─────────────────┘ └─────────────────┘
Step 1: Google Cloud ConsoleでOAuthクライアントID作成
- Google Cloud ConsoleでFirebaseと同じプロジェクトを選択
- 「APIとサービス」→「認証情報」→「OAuthクライアントID」を作成
- アプリケーションの種類: Chrome拡張機能を選択
Step 2: manifest.jsonの設定
{
"manifest_version": 3,
"name": "Your Extension",
"version": "1.0",
"permissions": ["identity", "storage"],
"oauth2": {
"client_id": "xxxxxxxxxxxxx.apps.googleusercontent.com",
"scopes": ["openid", "email", "profile"]
},
"key": "MIIBIjANBgkqh..."
}
| 項目 | 説明 |
|---|---|
permissions.identity | chrome.identity APIの使用に必要 |
oauth2.client_id | Google Cloud Consoleで作成したID |
oauth2.scopes | 取得する情報の範囲 |
key | 拡張機能IDを固定するための公開鍵 |
Step 3: Firebase SDKをローカルに配置
CDNが使えないため、SDKファイルをダウンロードして同梱する。
curl -o lib/firebase-app-compat.js \
https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js
curl -o lib/firebase-auth-compat.js \
https://www.gstatic.com/firebasejs/10.8.0/firebase-auth-compat.js
curl -o lib/firebase-firestore-compat.js \
https://www.gstatic.com/firebasejs/10.8.0/firebase-firestore-compat.js
Step 4: Firebase設定の初期化
// js/firebase-config.ts
const firebaseConfig = {
apiKey: "AIzaSy...",
authDomain: "your-project.firebaseapp.com",
projectId: "your-project",
storageBucket: "your-project.appspot.com",
messagingSenderId: "123456789",
appId: "1:123456789:web:abc123",
};
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const db = firebase.firestore();
Step 5: chrome.identity APIによる認証サービス
// js/auth-service.ts
const ExtensionAuthService = {
currentUser: null as firebase.User | null,
async signInWithGoogle(): Promise<firebase.User> {
return new Promise((resolve, reject) => {
chrome.identity.getAuthToken(
{ interactive: true },
async (token) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
return;
}
try {
const credential =
firebase.auth.GoogleAuthProvider.credential(null, token);
const result =
await firebase.auth().signInWithCredential(credential);
this.currentUser = result.user;
resolve(result.user);
} catch (error) {
// トークンが無効な場合はキャッシュをクリアして再試行
chrome.identity.removeCachedAuthToken({ token }, () => {
reject(error);
});
}
}
);
});
},
async signOut(): Promise<void> {
return new Promise((resolve) => {
chrome.identity.getAuthToken(
{ interactive: false },
(token) => {
if (token) {
chrome.identity.removeCachedAuthToken(
{ token },
async () => {
await firebase.auth().signOut();
this.currentUser = null;
resolve();
}
);
} else {
firebase.auth().signOut();
this.currentUser = null;
resolve();
}
}
);
});
},
onAuthStateChanged(callback: (user: firebase.User | null) => void) {
firebase.auth().onAuthStateChanged((user) => {
this.currentUser = user;
callback(user);
});
},
};
Step 6: popup.htmlとログイン処理
// popup.ts
document.addEventListener("DOMContentLoaded", () => {
ExtensionAuthService.onAuthStateChanged(updateUI);
document
.getElementById("btn-login")!
.addEventListener("click", async () => {
try {
await ExtensionAuthService.signInWithGoogle();
} catch (error) {
console.error("Login failed:", error);
}
});
document
.getElementById("btn-logout")!
.addEventListener("click", async () => {
await ExtensionAuthService.signOut();
});
document
.getElementById("btn-sync")!
.addEventListener("click", async () => {
const uid = firebase.auth().currentUser!.uid;
const localData = await chrome.storage.local.get("petapeta_data");
await db
.collection("users")
.doc(uid)
.collection("data")
.doc("bookmarks")
.set({
lists: localData.petapeta_data?.lists || [],
updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
});
});
});
function updateUI(user: firebase.User | null) {
const loginArea = document.getElementById("login-area")!;
const userArea = document.getElementById("user-area")!;
if (user) {
loginArea.classList.add("hidden");
userArea.classList.remove("hidden");
(document.getElementById("user-avatar") as HTMLImageElement).src =
user.photoURL || "";
document.getElementById("user-name")!.textContent =
user.displayName || "";
} else {
loginArea.classList.remove("hidden");
userArea.classList.add("hidden");
}
}
拡張機能IDの固定
開発中の拡張機能IDは読み込みごとに変わる可能性がある。OAuthで問題になるため、公開鍵で固定する。
# 秘密鍵を生成
openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -out key.pem
# 公開鍵を抽出(manifest.jsonのkeyに使用)
openssl rsa -in key.pem -pubout -outform DER | openssl base64 -A
よくあるエラーと対処法
| エラー | 原因 | 対処 |
|---|---|---|
| "OAuth2 not granted or revoked" | OAuth設定の不一致 | Cloud ConsoleのクライアントIDとmanifest.jsonの一致を確認 |
| "Invalid token" | トークン期限切れ | removeCachedAuthToken()でキャッシュクリア後に再取得 |
| "The extension is not authorized" | 拡張機能IDの不一致 | manifest.jsonにkeyを追加してIDを固定 |
Firestoreセキュリティルール
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
Before/After表
| 項目 | Before | After |
|---|---|---|
| 認証方式 | signInWithPopup()(CSPエラー) | chrome.identity.getAuthToken()(Chrome専用API) |
| SDK読み込み | CDN経由(CSPエラー) | ローカルファイルとして同梱 |
| データ保存先 | ローカルストレージのみ | Firestore(クロスデバイス同期対応) |
| トークン管理 | なし | chrome.identityによる安全な管理 + キャッシュクリア |
| 拡張機能ID | 読み込みごとに変動 | 公開鍵で固定 |
まとめ
Chrome拡張機能からFirebaseに接続するには、chrome.identityAPIによる認証、SDKのローカル配置、拡張機能IDの固定、Firestoreセキュリティルールの設定が必要となる。一度セットアップすればWeb版と同じFirestoreにアクセスでき、クロスデバイスでのデータ同期が実現する。
この記事は、開発の記録をもとに Claude Code が下書きし、私が確認して公開しています。