メインコンテンツまでスキップ
バージョン: 0.4.2

🔐 認証ユーティリティ

Nodeblocks SDKは、トークン管理、検証、セキュリティのための包括的な認証ユーティリティを提供します。これらのユーティリティは、ベアラートークン、Cookieベース認証、および異なるユースケース用の様々なトークンタイプを処理します。


🎯 概要

認証ユーティリティは、ユーザーとアプリケーション認証の両方のための安全なトークン生成、検証、および管理を提供します。複数のトークンタイプとセキュリティ検証メカニズムをサポートします。

主要機能

  • 複数のトークンタイプ: ユーザーアクセス、アプリアクセス、リフレッシュ、ワンタイムトークン
  • セキュリティ検証: フィンガープリント、IP、ユーザーエージェント検証
  • 柔軟な認証: ベアラートークンとCookieベース認証
  • JWT統合: JSON Web Token署名と検証

🔑 トークン生成

generateUserAccessToken

セキュリティ検証メタデータ付きの暗号化ユーザーアクセストークンを作成します。

import { utils } from '@nodeblocks/backend-sdk';

const { generateUserAccessToken } = utils;

const token = generateUserAccessToken(
authSecrets,
{ jwtSignOptions: { expiresIn: '24h' }, stateful: true },
userId,
{
fingerprint: 'device-fingerprint',
ip: '192.168.1.1',
domain: 'example.com',
userAgent: 'Mozilla/5.0...'
}
);

パラメーター:

  • authSecrets: 暗号化/署名用の認証シークレット
  • opts: JWTオプションとステートフル設定
  • userId: ユーザー識別子
  • tokenVerification: 検証用のセキュリティコンテキスト

generateAppAccessToken

サービス間通信用の暗号化アプリアクセストークンを作成します。

import { utils } from '@nodeblocks/backend-sdk';

const { generateAppAccessToken } = utils;

const token = generateAppAccessToken(authSecrets, 'app-service-id');

パラメーター:

  • authSecrets: 認証シークレット
  • appId: アプリケーション識別子

generateRefreshToken

セッション管理用の暗号化リフレッシュトークンを作成します。

import { utils } from '@nodeblocks/backend-sdk';

const { generateRefreshToken } = utils;

const token = generateRefreshToken(
authSecrets,
userId,
{
fingerprint: 'device-fingerprint',
ip: '192.168.1.1',
userAgent: 'Mozilla/5.0...'
}
);

パラメーター:

  • authSecrets: 認証シークレット
  • userId: ユーザー識別子
  • tokenVerification: セキュリティコンテキスト

generateOnetimeToken

一時アクセス用のワンタイムトークンを作成します。

import { utils } from '@nodeblocks/backend-sdk';

const { generateOnetimeToken } = utils;

const token = generateOnetimeToken(
authSecrets,
{ expiresIn: '15m' },
userId,
'email-verification'
);

パラメーター:

  • authSecrets: 認証シークレット
  • opts: 有効期限設定
  • userId: ユーザー識別子
  • purpose: トークンの目的

🔍 トークン認証

getBearerTokenInfo

Authorizationヘッダーからベアラートークンを抽出して検証します。

import { validators } from '@nodeblocks/backend-sdk';

const { getBearerTokenInfo } = validators;

const authValidator = verifyAuthentication(getBearerTokenInfo);

const protectedRoute = withRoute({
method: 'GET',
path: '/protected',
validators: [authValidator],
handler: protectedHandler,
});

動作:

  • ✅ 有効なベアラートークンの場合はトークン情報を返す
  • ❌ 無効または欠落している場合はエラーをスロー
  • ヘッダー形式: Authorization: Bearer <token>

getCookieTokenInfo

Cookieからトークンを抽出して検証します。

import { validators } from '@nodeblocks/backend-sdk';

const { getCookieTokenInfo } = validators;

// カスタムCookie名で設定
const cookieAuthenticator = getCookieTokenInfo('auth-token');

const cookieProtectedRoute = withRoute({
method: 'GET',
path: '/dashboard',
validators: [verifyAuthentication(cookieAuthenticator)],
handler: dashboardHandler,
});

パラメーター:

  • cookieName: 認証トークンを含むCookie名(デフォルト: 'token')

🛡️ セキュリティ検証

トークン検証コンテキスト

interface TokenVerification {
fingerprint?: string; // デバイスフィンガープリント
ip?: string; // クライアントIPアドレス
userAgent?: string; // ブラウザーユーザーエージェント
domain?: string; // リクエストドメイン
}

セキュリティ強化の例

import { utils } from '@nodeblocks/backend-sdk';

const { generateUserAccessToken } = utils;

// 高セキュリティトークン生成
const secureToken = generateUserAccessToken(
authSecrets,
{
jwtSignOptions: { expiresIn: '1h' }, // 短い有効期限
stateful: true // サーバーサイド検証
},
userId,
{
fingerprint: generateDeviceFingerprint(request),
ip: request.ip,
userAgent: request.get('User-Agent'),
domain: request.get('Host')
}
);

🔧 認証設定

認証シークレット設定

interface AuthSecrets {
authEncSecret: string; // 暗号化シークレット
authSignSecret: string; // 署名シークレット
}

const authSecrets: AuthSecrets = {
authEncSecret: process.env.AUTH_ENC_SECRET,
authSignSecret: process.env.AUTH_SIGN_SECRET,
};

JWT設定オプション

interface JWTOptions {
jwtSignOptions?: {
expiresIn?: string; // 有効期限(例: '1h', '24h', '7d')
issuer?: string; // トークン発行者
audience?: string; // 対象オーディエンス
};
stateful?: boolean; // サーバーサイド検証の有効化
}

🎯 認証パターン

ベアラートークン認証

import { validators } from '@nodeblocks/backend-sdk';

const { verifyAuthentication, getBearerTokenInfo } = validators;

const apiRoute = withRoute({
method: 'GET',
path: '/api/data',
validators: [verifyAuthentication(getBearerTokenInfo)],
handler: compose(
getData,
lift(formatResponse)
),
});

Cookie認証

import { validators } from '@nodeblocks/backend-sdk';

const { verifyAuthentication, getCookieTokenInfo } = validators;

const webRoute = withRoute({
method: 'GET',
path: '/dashboard',
validators: [verifyAuthentication(getCookieTokenInfo('session'))],
handler: compose(
getDashboardData,
lift(renderDashboard)
),
});

ハイブリッド認証

// ベアラートークンまたはCookieをサポート
const hybridAuthenticator = (payload: RouteHandlerPayload) => {
try {
return getBearerTokenInfo(payload);
} catch {
return getCookieTokenInfo('auth')(payload);
}
};

const flexibleRoute = withRoute({
method: 'GET',
path: '/api/flexible',
validators: [verifyAuthentication(hybridAuthenticator)],
handler: flexibleHandler,
});

🔄 トークンリフレッシュ

リフレッシュトークンの実装

import { utils } from '@nodeblocks/backend-sdk';

const { generateUserAccessToken, generateRefreshToken } = utils;

const refreshTokenHandler = async (payload: RouteHandlerPayload) => {
const { refreshToken } = payload.params.requestBody;

// リフレッシュトークンを検証
const tokenData = await validateRefreshToken(refreshToken);

if (!tokenData) {
throw new NodeblocksError(401, '無効なリフレッシュトークンです');
}

// 新しいアクセストークンを生成
const newAccessToken = generateUserAccessToken(
authSecrets,
{ jwtSignOptions: { expiresIn: '1h' } },
tokenData.userId,
tokenData.verification
);

return ok(mergeData(payload, { accessToken: newAccessToken }));
};

🎯 ベストプラクティス

1. セキュアなトークン生成

// 良い - セキュリティコンテキスト付き
const secureToken = generateUserAccessToken(
authSecrets,
{ jwtSignOptions: { expiresIn: '1h' }, stateful: true },
userId,
{
fingerprint: deviceFingerprint,
ip: clientIP,
userAgent: request.userAgent
}
);

// 悪い - セキュリティコンテキストなし
const insecureToken = generateUserAccessToken(authSecrets, {}, userId);

2. 適切な有効期限

// アクセストークン - 短期
const accessToken = generateUserAccessToken(
authSecrets,
{ jwtSignOptions: { expiresIn: '1h' } },
userId,
verification
);

// リフレッシュトークン - 長期
const refreshToken = generateRefreshToken(
authSecrets,
userId,
verification
);

3. 環境変数の使用

// 良い - 環境変数から読み込み
const authSecrets = {
authEncSecret: process.env.AUTH_ENC_SECRET,
authSignSecret: process.env.AUTH_SIGN_SECRET,
};

// 悪い - ハードコードされたシークレット
const authSecrets = {
authEncSecret: 'hardcoded-secret', // セキュリティリスク
authSignSecret: 'another-secret',
};

➡️ 次へ

エンティティユーティリティについて学習して、データベースエンティティの作成と管理を理解しましょう!