メインコンテンツまでスキップ

外部認証

サードパーティサービスのコネクタ向け OAuth2 トークンを管理する​

External Auth を使用する理由​

アプリケーションが Google Drive や Google Calendar などのサードパーティサービスでユーザー固有のデータにアクセスするには、各ユーザーが OAuth2 を介してアプリを認可する必要があります。認可によって生成されるアクセストークンとリフレッシュトークンは、安全に保存し、有効期限が切れたら更新し、ユーザーごとに分離する必要があります。

External Auth を使用しない場合、アプリケーションは OAuth2 トークンのライフサイクル全体を自分で実装する必要があります。これには、認可コードとトークンの交換、トークンの暗号化と保存、期限切れのトークンの更新、認証情報のクリーンアップが含まれます。

External Auth を使用すると、保存するのは認可コードだけです。トークンの保存、更新、ユーザーごとの分離を含む、OAuth2 ライフサイクルの残りの処理は Squid が管理します。

Backend code
// Save the user's authorization code after they consent
// Squid exchanges it for tokens and stores them encrypted at rest
const externalAuth = this.squid.externalAuth('google_drive');
await externalAuth.saveAuthCode(authCode, userId);

// Later, get a valid access token (auto-refreshed if expired)
const { accessToken } = await externalAuth.getAccessToken(userId);

トークンの保存も更新ロジックも不要です。認可コードを渡すだけで、アクセストークンを取得できます。

概要​

External Authentication モジュールは、サードパーティサービスのコネクタにおける OAuth2 認証フローを統一的に処理する方法を提供します。認可コード、アクセストークン、トークンの自動更新を管理し、ユーザーに安全な認証体験を提供します。

仕組み​

  1. ユーザーの認可: ユーザーをサードパーティの OAuth 同意画面に誘導し、アプリへのアクセスを許可してもらいます
  2. トークンの交換: フロントエンドが認可コードをバックエンド関数に渡し、関数が Squid に保存します。Squid は認可コードをアクセストークンとリフレッシュトークンに交換します。
  3. 自動管理: Squid はトークンをユーザーごとに暗号化して保存し、有効期限が切れる前に自動的に更新します

ステップ 1 をフロントエンドに実装し、ステップ 2 でバックエンド関数を呼び出します。残りは Squid が処理します。

主な機能​

  • 安全なトークン保存: トークンは保存時に暗号化され、ユーザーごとに安全に保存されます
  • 自動更新: アクセストークンは有効期限が切れる際に更新され(30 秒のバッファあり)、さらにバックグラウンドジョブによって 5 分ごとに先回りして更新されます
  • マルチユーザー対応: 各ユーザーのトークンは一意の識別子を使用して分離されます
  • コネクタ非依存: OAuth2 に準拠した任意のサービスコネクタで動作します

External Auth の使用場面​

シナリオ推奨される方法
サードパーティの OAuth2 サービスでユーザーデータにアクセスするExternal Auth
自分のアプリでユーザーを認証するAuthentication を使用する
共有 API キーでサードパーティの API を呼び出すExecutable で Secrets を使用する

クイックスタート​

前提条件​

  1. Squid Console で設定済みの、OAuth2 を必要とするコネクタ(例: Google Drive、Google Calendar)
  2. サードパーティサービスの OAuth2 認証情報(Client ID、Client Secret)がコネクタの設定に追加されていること
  3. NPM から @squidcloud/backend パッケージをインストールした Squid バックエンドプロジェクト

ステップ 1: External Auth 用のバックエンド関数を作成する​

External Auth には Squid API キーが必要ですが、これをクライアント側のコードに含めるべきではありません。代わりに、External Auth のすべてのロジックをexecutables を介してバックエンドで実行し、API キーをサーバー上で安全に保持します。フロントエンドは OAuth リダイレクトの処理と、これらのバックエンド関数の呼び出しのみを行います。これらのバックエンド関数は、必ずセキュリティルールを使用して保護してください。

認可コードを保存し、アクセストークンを取得するサービスを作成します。

Backend code
import { executable, SquidService } from '@squidcloud/backend';

export class ExternalAuthService extends SquidService {
@executable()
async saveExternalAuthCode(
connectorId: string,
authCode: string,
userId: string
): Promise<{ accessToken: string; expirationTime: Date }> {
const externalAuth = this.squid.externalAuth(connectorId);
return externalAuth.saveAuthCode(authCode, userId);
}

@executable()
async getExternalAccessToken(
connectorId: string,
userId: string
): Promise<{ accessToken: string; expirationTime: Date }> {
const externalAuth = this.squid.externalAuth(connectorId);
return externalAuth.getAccessToken(userId);
}
}

ステップ 2: ユーザーを OAuth 同意画面に誘導する​

フロントエンドでサードパーティの認可 URL を構築し、ユーザーをリダイレクトします。必要なパラメータは OAuth プロバイダーによって異なります。

たとえば、Google の場合は次のようになります。

Client code
function startOAuth() {
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', 'your-google-client-id');
authUrl.searchParams.set('redirect_uri', 'https://yourapp.com/oauth/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'https://www.googleapis.com/auth/drive.readonly');
authUrl.searchParams.set('access_type', 'offline'); // Required to receive a refresh token

window.location.href = authUrl.toString();
}
プロバイダーごとの違い

OAuth2 プロバイダーごとに、認可 URL、スコープ、パラメータの要件は異なります。正確な要件については、必ずプロバイダーの OAuth2 ドキュメントを参照してください。

ステップ 3: 認可コードを保存する​

ユーザーが同意し、認可コードとともにアプリにリダイレクトされたら、そのコードをバックエンド関数に渡します。

Client code
async function handleOAuthCallback(userId: string) {
const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get('code');

if (authCode) {
await squid.executeFunction(
'saveExternalAuthCode',
'google_drive', // Your connector ID
authCode,
userId
);
}
}

認可コードは一度しか使用できず、通常は数分以内に有効期限が切れるため、速やかに交換してください。

ステップ 4: バックエンド関数でアクセストークンを使用する​

認可コードを保存したら、任意のバックエンド関数で有効なアクセストークンを取得し、外部 API を呼び出せます。

Backend code
@executable()
async listFiles(userId: string): Promise<any> {
const externalAuth = this.squid.externalAuth('google_drive');
const { accessToken } = await externalAuth.getAccessToken(userId);

const response = await fetch('https://www.googleapis.com/drive/v3/files', {
headers: { Authorization: `Bearer ${accessToken}` },
});

return (await response.json()) as { files: Array<{ id: string; name: string }> };
}

トークンの有効期限が切れている場合、またはまもなく切れる場合、Squid が自動的に更新します。

基本概念​

ユーザー識別子​

saveAuthCode と getAccessToken の identifier パラメータは、トークンを特定のユーザーに関連付けます。認証プロバイダーのユーザー ID など、アプリケーション全体で一貫した、ユーザーごとに一意の識別子を使用してください。

各ユーザーは OAuth フローを一度完了する必要があります。その後は、識別子を使用して、そのユーザーの有効なアクセストークンをいつでも取得できます。

PKCE​

認可リクエストに PKCE の code challenge が含まれていた場合は、トークン交換を完了できるように、対応する code verifier を saveAuthCode の第 3 引数として渡します。

Backend code
import { executable, SquidService } from '@squidcloud/backend';

export class ExternalAuthService extends SquidService {
@executable()
async saveAuthCodeWithPkce(authCode: string, codeVerifier: string) {
const userId = this.getUserAuth()?.userId;
if (!userId) throw new Error('Unauthorized');

const externalAuth = this.squid.externalAuth('YOUR_CONNECTOR_ID');
return externalAuth.saveAuthCode(authCode, userId, codeVerifier);
}
}

トークンのライフサイクル​

Squid はトークンのライフサイクル全体を管理します。

段階処理内容
保存saveAuthCode() が認可コードをアクセストークンとリフレッシュトークンに交換し、暗号化して保存します
取得getAccessToken() が有効なアクセストークンを返します。必要に応じて自動的に更新します
自動更新トークンは有効期限の 30 秒前から更新されます。また、バックグラウンドジョブが 5 分ごとにトークンを先回りして更新します
クリーンアップリフレッシュトークンが恒久的に無効になったトークン(ユーザーがアクセスを取り消した場合など)は自動的に削除されます

対応コネクタ​

External Auth は OAuth2 に準拠した任意のコネクタで動作します。現在対応しているコネクタには、以下が含まれます。

API リファレンス​

API 呼び出しの詳細は、SDK リファレンスドキュメントを参照してください。たとえば、squid.externalAuth(connectorId) は、指定されたコネクタの ExternalAuthClient を返します。

エラー処理​

よくあるエラー​

エラー原因解決方法
Integration not foundconnectorId が設定済みのコネクタと一致しないコネクタ ID が Squid Console のものと一致することを確認する
External auth not supported for integration typeコネクタの種類が OAuth2 に対応していないOAuth2 認証に対応したコネクタを使用する
No external auth tokens foundユーザーが OAuth フローを完了する前に getAccessToken が呼び出されたユーザーが認可を完了し、saveAuthCode が呼び出されたことを確認する
Refresh token expired or invalidユーザーがアクセスを取り消したか、リフレッシュトークンの有効期限が切れたOAuth フローを再度完了して再認可するようユーザーに促す
OAuth token exchange failed認可コードが無効、期限切れ、または使用済みであるユーザーを同意画面にリダイレクトして新しい認可コードを要求する
Missing client secretコネクタに OAuth の client secret が設定されていないSquid Console でコネクタの設定に client secret を追加する

バックエンド関数でのエラー処理​

Backend code
@executable()
async getExternalAccessToken(
connectorId: string,
userId: string
): Promise<{ accessToken: string; expirationTime: Date }> {
try {
const externalAuth = this.squid.externalAuth(connectorId);
return await externalAuth.getAccessToken(userId);
} catch (error: any) {
if (error.message.includes('No external auth tokens found')) {
// User hasn't authorized yet
throw new Error('USER_NOT_AUTHORIZED');
} else if (error.message.includes('Refresh token has expired')) {
// User needs to re-authorize
throw new Error('REAUTHORIZATION_REQUIRED');
}
throw error;
}
}
Client code
try {
const { accessToken } = await squid.executeFunction(
'getExternalAccessToken',
'google_drive',
userId
);
} catch (error: any) {
if (error.message.includes('USER_NOT_AUTHORIZED') ||
error.message.includes('REAUTHORIZATION_REQUIRED')) {
// Redirect user to the OAuth consent screen
startOAuth();
} else {
console.error('Failed to get access token:', error.message);
}
}

ベストプラクティス​

  1. External Auth はバックエンドで使用する: External Auth には Squid API キーが必要です。このキーをクライアント側のコードで公開してはなりません。すべての External Auth 操作にバックエンド executables を使用し、API キーをサーバー上に保持してください。フロントエンドは OAuth リダイレクトの処理とバックエンド関数の呼び出しのみを行います。
  2. 一貫した識別子を使用する: 特定のユーザーに対するすべての External Auth 呼び出しで、同じ一意の識別子(認証プロバイダーのユーザー ID など)を使用します
  3. HTTPS のみを使用する: 本番環境では、OAuth リダイレクト URI に必ず HTTPS を使用します
  4. スコープを最小限にする: アプリケーションに必要な OAuth スコープのみを要求します
  5. トークンは Squid に管理させる: トークンを自分のアプリケーションに保存しないでください。常に getAccessToken を呼び出して、更新済みの有効なトークンを取得します
  6. 再認可を適切に処理する: トークンの更新に失敗した場合は、汎用的なエラーを表示するのではなく、ユーザーを OAuth フローに再度誘導します
  7. 認可コードを速やかに交換する: 認可コードは一度しか使用できず、すぐに有効期限が切れます。ユーザーがアプリにリダイレクトされたら、すぐに saveAuthCode を呼び出します

コード例​

Google Drive: ファイルの一覧を取得する​

Google Drive のファイル一覧を取得するバックエンド関数を含む完全な例です。

バックエンド:

Backend code
import { executable, SquidService } from '@squidcloud/backend';

interface DriveFile {
id: string;
name: string;
mimeType: string;
}

export class DriveService extends SquidService {
private readonly CONNECTOR_ID = 'google_drive';

@executable()
async saveDriveAuthCode(
authCode: string,
userId: string
): Promise<{ accessToken: string; expirationTime: Date }> {
const externalAuth = this.squid.externalAuth(this.CONNECTOR_ID);
return externalAuth.saveAuthCode(authCode, userId);
}

@executable()
async listDriveFiles(userId: string): Promise<DriveFile[]> {
const externalAuth = this.squid.externalAuth(this.CONNECTOR_ID);
const { accessToken } = await externalAuth.getAccessToken(userId);

const response = await fetch(
'https://www.googleapis.com/drive/v3/files?pageSize=10',
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);

if (!response.ok) {
throw new Error(`Google Drive API error: ${response.status}`);
}

const data = (await response.json()) as { files: DriveFile[] };
return data.files;
}
}

フロントエンド:

Client code
// Step 1: Redirect the user to Google's OAuth consent screen
function startGoogleDriveAuth() {
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', 'your-google-client-id');
authUrl.searchParams.set('redirect_uri', 'https://yourapp.com/oauth/callback');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('scope', 'https://www.googleapis.com/auth/drive.readonly');
authUrl.searchParams.set('access_type', 'offline');
authUrl.searchParams.set('prompt', 'consent');

window.location.href = authUrl.toString();
}

// Step 2: Handle the OAuth callback and save the auth code
async function handleOAuthCallback(userId: string) {
const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get('code');

if (!authCode) {
throw new Error('No authorization code received');
}

await squid.executeFunction('saveDriveAuthCode', authCode, userId);
}

// Step 3: List the user's Drive files
async function listDriveFiles(userId: string) {
const files = await squid.executeFunction('listDriveFiles', userId);
console.log('Files:', files);
return files;
}

Google Calendar: 予定されているイベントを取得する​

バックエンド:

Backend code
import { executable, SquidService } from '@squidcloud/backend';

interface CalendarEvent {
id: string;
summary: string;
start: { dateTime: string };
}

export class CalendarService extends SquidService {
private readonly CONNECTOR_ID = 'google_calendar';

@executable()
async saveCalendarAuthCode(
authCode: string,
userId: string
): Promise<{ accessToken: string; expirationTime: Date }> {
const externalAuth = this.squid.externalAuth(this.CONNECTOR_ID);
return externalAuth.saveAuthCode(authCode, userId);
}

@executable()
async getUpcomingEvents(userId: string): Promise<CalendarEvent[]> {
const externalAuth = this.squid.externalAuth(this.CONNECTOR_ID);
const { accessToken } = await externalAuth.getAccessToken(userId);

const now = new Date().toISOString();
const url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=${now}&maxResults=10&orderBy=startTime&singleEvents=true`;

const response = await fetch(url, {
headers: { Authorization: `Bearer ${accessToken}` },
});

if (!response.ok) {
throw new Error(`Google Calendar API error: ${response.status}`);
}

const data = (await response.json()) as { items: CalendarEvent[] };
return data.items;
}
}

フロントエンド:

Client code
// After the user completes OAuth for Google Calendar
async function handleCalendarCallback(userId: string) {
const urlParams = new URLSearchParams(window.location.search);
const authCode = urlParams.get('code');

if (authCode) {
await squid.executeFunction('saveCalendarAuthCode', authCode, userId);
}
}

// Fetch upcoming events
async function getUpcomingEvents(userId: string) {
const events = await squid.executeFunction('getUpcomingEvents', userId);
console.log('Upcoming events:', events);
return events;
}

関連項目​