メインコンテンツまでスキップ
バージョン: 0.5.0 (最新)

🔐 認証サービス

Testing Status

認証サービスは、アイデンティティの登録、ログイン、ログアウト、トークン管理を提供する完全な認証システムです。JWTベースのセキュリティおよびクッキー対応を備えています。


🚀 クイックスタート

import express from 'express';
import { services, middlewares, types, drivers } from '@nodeblocks/backend-sdk';

const { getMongoClient, createGoogleOAuthDriver } = drivers;
const client = getMongoClient('mongodb://localhost:27017', 'dev');

express()
.use(
services.authService(
{
identities: client.collection('identities'),
onetimetokens: client.collection('onetimetokens'),
invitations: client.collection('invitations'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
maxFailedLoginAttempts: 5,
accessTokenExpireTime: '2h',
refreshTokenExpireTime: '2d',
verifyEmailConfig: {
enabled: true,
emailConfig: {
bodyTemplate: 'Hello {{email}}',
subject: 'Welcome to our app',
urlTemplate: 'https://example.com/verify-email?token={{token}}',
},
sender: 'noreply@example.com'
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="{{url}}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token={{token}}&email={{email}}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
},
{
mailService: {
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
},
googleOAuthDriver: createGoogleOAuthDriver(
process.env.GOOGLE_CLIENT_ID!,
process.env.GOOGLE_CLIENT_SECRET!,
'https://example.com/auth/oauth/google/callback'
)
}
)
)
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));

📋 エンドポイント概要

メソッドパス説明
認証エンドポイント
POST/auth/register新しいアイデンティティアカウントを登録
POST/auth/loginアイデンティティを認証しトークンを受け取る
POST/auth/logoutログアウトしトークンを無効化
メール確認エンドポイント
POST/auth/:identityId/send-verification-emailアイデンティティにメール確認を送信
POST/auth/confirm-email確認トークンでメールを確認
メール管理エンドポイント
PATCH/auth/:identityId/change-emailメール変更プロセスを開始
POST/auth/confirm-new-email新しいメールアドレスを確認
パスワード管理エンドポイント
POST/auth/send-reset-password-link-emailパスワード再設定メールを送信
POST/auth/reset-passwordパスワード再設定を完了
PATCH/auth/:identityId/change-passwordユーザーパスワードを変更
アカウント管理エンドポイント
POST/auth/activateユーザーアカウントを有効化
POST/auth/deactivateユーザーアカウントを無効化
トークン管理エンドポイント
POST/auth/token/checkアクセストークンを検証
招待エンドポイント
POST/invitations招待を新規作成
GET/invitations招待を任意のフィルタで一覧取得
GET/invitations/:invitationIdIDで招待を取得
DELETE/invitations/:invitationId招待を削除
OAuth エンドポイント
GET/auth/oauth/googleGoogle OAuth フローを開始
GET/auth/oauth/google/callbackGoogle OAuth コールバックを処理(⚠️ 機能は限定的)

🗄️ エンティティスキーマ

認証サービスは以下のスキーマでアイデンティティを管理します:

アイデンティティエンティティ

{
"id": "string",
"email": "string",
"password": "string",
"attempts": "number",
"locked": "boolean",
"createdAt": "string",
"updatedAt": "string",
"typeId": "string"
}

フィールド詳細

フィールド自動生成必須説明
idstring一意な識別子(UUID)
emailstringアイデンティティのメールアドレス
passwordstringハッシュ化されたパスワード
attemptsnumber失敗したログイン試行回数
lockedbooleanアカウントのロック状態
createdAtstring作成日時
updatedAtstring更新日時
typeIdstringロール識別子(例:管理者は "100"、一般は "001")

補足フィールド詳細:

  • attempts: 連続した失敗ログイン回数を追跡します。しきい値(設定可能)を超えると自動でロックされます。

  • locked: 失敗回数の超過または管理操作によりロックされているかどうか。ロック中は認証できません。

  • typeId: システム内のロール/権限を示す識別子。サービスごとに調整可能。例:

    • "100": 管理者(フルアクセス)
    • "001": 一般ユーザー(基本権限)
    • "000": ゲスト(最小権限)
    • 必要に応じてカスタムロールを追加可能

招待エンティティ

認証サービスは以下のスキーマで招待も管理します:

{
"id": "string",
"email": "string",
"fromIdentityId": "string",
"orgId": "string",
"role": "string",
"status": "string",
"createdAt": "string",
"updatedAt": "string"
}

招待フィールド詳細

フィールド自動生成必須説明
idstring一意な識別子(UUID)
emailstring招待先のメールアドレス
fromIdentityIdstring招待送信者のアイデンティティID
orgIdstring招待先の組織ID
rolestring組織でのロール
statusstring招待の状態(例:pending / accepted)
createdAtstring作成日時
updatedAtstring更新日時

🔐 認証ヘッダー

保護されたエンドポイントでは、以下のヘッダーを含めてください:

Authorization: Bearer <access_token>
x-nb-fingerprint: <device_fingerprint>

⚠️ 重要: 認可時にフィンガープリントを指定した場合、認証済みの全リクエストで x-nb-fingerprint ヘッダーが必須です。欠如している場合は 401 Unauthorized が返ります。


🔧 APIエンドポイント

1. アイデンティティ登録

メールアドレスとパスワードで新規アイデンティティを登録します。

リクエスト:

  • Method: POST
  • Path: /auth/register
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
emailstring✅*アイデンティティのメールアドレス
passwordstringパスワード
tokenstring✅*招待トークン

*email または token のいずれかが必須(同時指定不可)。

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(email+password または token+password 必須)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123"
}'

トークン指定のリクエスト例(既存ユーザー):

curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"token": "invitation-token",
"password": "securepassword123"
}'

成功レスポンス:

HTTP/1.1 201 Created
Content-Type: application/json

エラーレスポンス:

メールが既に存在する場合:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
"error": {
"message": "unable to register \"user@example.com\""
}
}

必須フィールドが欠落している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'",
"request body must have required property 'token'",
"request body must match exactly one schema in oneOf"
]
}
}

2. ログイン

資格情報を認証し、アクセストークンとリフレッシュトークンを受け取ります。

リクエスト:

  • Method: POST
  • Path: /auth/login
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
emailstringメールアドレス
passwordstringパスワード
fingerprintstring端末フィンガープリント

レスポンスボディ:

フィールド説明
accessTokenstringAPI認証用のJWTアクセストークン
idstringアイデンティティID
refreshTokenstringJWTリフレッシュトークン

バリデーション:

  • スキーマ検証: 自動適用(email, password 必須)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123",
"fingerprint": "device-fingerprint"
}'

成功レスポンス:

HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Credentials: true
Set-Cookie: accessToken=...; Path=/
Set-Cookie: refreshToken=...; Path=/

{
"accessToken": "c911c0dd107f8d7e92c0608aa149d041:dee2...",
"id": "0b3839a6-92b4-4044-a13b-ed834a105646",
"refreshToken": "9f0cad0da1ceec15c01de729a2359236:2acc8ee1b57fd971473..."
}

エラーレスポンス:

資格情報が不正な場合:

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"error": {
"message": "wrong credentials provided"
}
}

3. ログアウト

ログアウトし、リフレッシュトークンを無効化します。

リクエスト:

  • Method: POST
  • Path: /auth/logout
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須

リクエストボディ:

フィールド必須説明
ボディなし-不要。Authorizationヘッダーのアクセストークンを使用

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: なし
  • ルートバリデーション: 認証済みリクエスト(ベアラートークン)必須

リクエスト例:

curl -X POST {{host}}/auth/logout \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

リフレッシュトークンの無効化に失敗した場合:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "failed to delete refresh token"
}
}

4. 確認メール送信

アイデンティティのメールアドレス宛に確認用リンクを送信します。

リクエスト:

  • Method: POST
  • Path: /auth/:identityId/send-verification-email
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者または本人)

パスパラメータ:

フィールド必須説明
identityIdstringアイデンティティの一意なID

リクエストボディ:

フィールド必須説明
fingerprintstringセキュリティ用の端末フィンガープリント

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者または本人であること

リクエスト例:

curl -X POST {{host}}/auth/identity-12345/send-verification-email \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"fingerprint": "device-fingerprint"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

メール確認機能が無効な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verification email feature not enabled"
}
}

メールサービスが未設定の場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verification email feature requires a mail service to be provided"
}
}

メール設定が不足している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplate"
}
}

メール送信に失敗した場合:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to send verification email"
}
}

5. メール確認

確認トークンを使用してメールアドレスを確認します。

リクエスト:

  • Method: POST
  • Path: /auth/confirm-email
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
tokenstringメールに記載の確認トークン

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(token 必須)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/confirm-email \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-verification-token"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

トークンが無効な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Unable to verify token"
}
}

6. 招待の作成

サービスへの参加招待を新規作成します。

リクエスト:

  • Method: POST
  • Path: /invitations
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者)

リクエストボディ:

フィールド必須説明
emailstring招待先のメールアドレス
fromIdentityIdstring招待送信者のアイデンティティID
orgIdstring招待先の組織ID
rolestring組織内ロール

レスポンスボディ:

フィールド説明
invitationIdstring作成された招待の一意ID

バリデーション:

  • スキーマ検証: 自動適用(email, fromIdentityId 必須・追加プロパティ不可)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者権限必須

リクエスト例:

curl -X POST {{host}}/invitations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"email": "newuser@example.com",
"fromIdentityId": "392157b1-dc7a-4935-a6f9-a2d333b910ea"
"orgId": "org123",
"role": "member"
}'

成功レスポンス:

HTTP/1.1 201 Created
Content-Type: application/json

{
"invitationId": "62564a60-e720-4907-bb85-3afaa2729e0d"
}

エラーレスポンス:

必須フィールドが欠落している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'"
]
}
}

fromIdentityId が欠落している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'fromIdentityId'"
]
}
}

email の形式が不正な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must match format \"email\""
]
}
}

追加プロパティが含まれる場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"request body must NOT have additional properties"
]
}
}

招待の作成に失敗した場合:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to create invitation"
}
}

7. 招待一覧

招待をフィルター・ページング付きで取得します。

リクエスト:

  • Method: GET
  • Path: /invitations
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者)

クエリパラメータ:

フィールド必須説明
emailstring招待先メールでフィルター
fromIdentityIdstring招待送信者IDでフィルター
orgIdstring組織IDでフィルター
rolestringロールでフィルター
pagenumberページ番号
limitnumber1ページ件数

レスポンスボディ:

フィールド説明
emailstring招待先のメールアドレス
fromIdentityIdstring招待送信者のアイデンティティID
orgIdstring組織ID
rolestring組織内ロール
statusstring招待の状態(例: pending/accepted)
createdAtstring作成日時
idstring招待の一意ID
updatedAtstring更新日時

バリデーション:

  • スキーマ検証: 自動適用
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者権限必須

リクエスト例:

curl -X GET "{{host}}/invitations" \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

HTTP/1.1 200 OK
Content-Type: application/json

[
{
"email": "newuser@example.com",
"fromIdentityId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}
]

空レスポンス:

HTTP/1.1 200 OK
Content-Type: application/json

[]

8. 招待の取得(ID指定)

一意IDで特定の招待を取得します。

リクエスト:

  • Method: GET
  • Path: /invitations/:invitationId
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者)

パスパラメータ:

フィールド必須説明
invitationIdstring招待の一意ID

バリデーション:

  • スキーマ検証: 自動適用
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者権限必須

リクエスト例:

curl -X GET {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

HTTP/1.1 200 OK
Content-Type: application/json

{
"email": "newuser@example.com",
"fromIdentityId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}

エラーレスポンス:

招待が見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Invitation not found"
}
}

9. 招待の削除

一意IDで特定の招待を削除します。

リクエスト:

  • Method: DELETE
  • Path: /invitations/:invitationId
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者)

パスパラメータ:

フィールド必須説明
invitationIdstring招待の一意ID

バリデーション:

  • スキーマ検証: 自動適用
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者権限必須

リクエスト例:

curl -X DELETE {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

HTTP/1.1 204 OK
Content-Type: application/json

エラーレスポンス:

招待が見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Invitation not found"
}
}

10. メール変更の開始

新しいメールアドレスに確認メールを送信し、メール変更プロセスを開始します。

リクエスト:

  • Method: PATCH
  • Path: /auth/:identityId/change-email
  • ヘッダー:
    • Content-Type: application/json
  • 認可: ベアラートークン必須(管理者または本人)

パスパラメータ:

フィールド必須説明
identityIdstringアイデンティティの一意ID

リクエストボディ:

フィールド必須説明
emailstring新しいメールアドレス

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(email 必須・メール形式)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者または本人であること

リクエスト例:

curl -X PATCH {{host}}/auth/identity-12345/change-email \
-H "Content-Type: application/json" \
-d '{
"email": "newemail@example.com"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

メールが既に存在する場合:

HTTP/1.1 409 Conflict
Content-Type: application/json

{
"error": {
"message": "Email already exists"
}
}

アイデンティティが見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

11. 新しいメールの確認

ワンタイム確認トークンで新しいメールアドレスを確定します。

リクエスト:

  • Method: POST
  • Path: /auth/confirm-new-email
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
tokenstringメールの確認トークン

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(token 必須)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/confirm-new-email \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-verification-token"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

トークンが無効な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Invalid token"
}
}

12. パスワード再設定リンク送信

メールアドレスに基づいてパスワード再設定リンクを送信します。

リクエスト:

  • Method: POST
  • Path: /auth/send-reset-password-link-email
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
emailstringパスワード再設定用のメールアドレス

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(email 必須・メール形式)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/send-reset-password-link-email \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

メールが見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Email not found"
}
}

13. パスワード再設定の完了

トークンを検証し、新しいパスワードに更新して再設定を完了します。

リクエスト:

  • Method: POST
  • Path: /auth/reset-password
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <one-time-token>
  • 認可: ベアラートークン必須(ワンタイムトークン)

リクエストボディ:

フィールド必須説明
passwordstring新しいパスワード(8〜24文字、英小文字と数字を含む)

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(password 必須・セキュリティ要件を満たす)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/reset-password \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <one-time-token>" \
-d '{
"password": "newSecurePassword123"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

トークンが無効な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Invalid token"
}
}

パスワードが要件を満たさない場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"password must match pattern \"^(?=.*[a-z])(?=.*\\d)[a-zA-Z0-9?/_-]{8,24}$\""
]
}
}

14. パスワード変更

PATCH /auth/:identityId/change-password でパスワードを変更します。

リクエスト:

  • Method: PATCH
  • Path: /auth/:identityId/change-password
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須

パスパラメータ:

フィールド必須説明
identityIdstringアイデンティティの一意ID

リクエストボディ:

フィールド必須説明
passwordstring現在のパスワード(確認用)
newPasswordstring新しいパスワード(8〜24文字、英小文字と数字を含む)

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(password, newPassword 必須・要件を満たす)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者または本人であること

リクエスト例:

curl -X PATCH {{host}}/auth/identity-12345/change-password \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"password": "oldPassword123",
"newPassword": "newSecurePassword123"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

現在のパスワードが正しくない場合:

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"error": {
"message": "Current password is incorrect"
}
}

新しいパスワードが要件を満たさない場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"newPassword must match pattern \"^(?=.*[a-z])(?=.*\\d)[a-zA-Z0-9?/_-]{8,24}$\""
]
}
}

15. アカウント有効化

POST /auth/activate でアカウントを有効化します。

リクエスト:

  • Method: POST
  • Path: /auth/activate
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <token>
  • 認可: ベアラートークン必須(管理者)

リクエストボディ:

フィールド必須説明
identityIdstring有効化対象のアイデンティティID

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(identityId 必須)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者権限必須

リクエスト例:

curl -X POST {{host}}/auth/activate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"identityId": "identity-12345"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

アイデンティティが見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

メールが未確認の場合:

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
"error": {
"message": "Email must be verified before activation"
}
}

16. アカウント無効化

POST /auth/deactivate でアイデンティティを無効化します。

リクエスト:

  • Method: POST
  • Path: /auth/deactivate
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <token>
  • 認可: ベアラートークン必須(管理者または本人)

リクエストボディ:

フィールド必須説明
identityIdstring無効化対象のアイデンティティID

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: 自動適用(identityId 必須)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者または本人であること

リクエスト例:

curl -X POST {{host}}/auth/deactivate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"identityId": "identity-12345"
}'

成功レスポンス:

HTTP/1.1 204 No Content
Content-Type: application/json

エラーレスポンス:

アイデンティティが見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

メールが未確認の場合:

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
"error": {
"message": "Email must be verified before deactivation"
}
}

トークンが欠落している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Missing token header"
}
}

メール送信に失敗した場合:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to send email"
}
}

17. トークン検証

アクセストークンを検証し、その状態を返します。

リクエスト:

  • Method: POST
  • Path: /auth/token/check
  • ヘッダー:
    • Content-Type: application/json
  • 認可: 不要

リクエストボディ:

フィールド必須説明
tokenstring検証対象のトークン
targetstring任意の検証コンテキスト

レスポンスボディ:

フィールド説明
identityIdstring有効な場合のアイデンティティID

バリデーション:

  • スキーマ検証: 自動適用(token 必須)
  • ルートバリデーション: なし

リクエスト例:

curl -X POST {{host}}/auth/token/check \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-token-to-validate",
"target": "optional-target-context"
}'

成功レスポンス:

HTTP/1.1 200 OK
Content-Type: application/json

{
"identityId": "811ff0a3-a26f-447b-b68a-dd83ea4000b9"
}

エラーレスポンス:

トークンが無効な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Unable to verify token"
}
}

18. Google OAuth 開始

Google の認可ページにリダイレクトして OAuth 認証フローを開始します。ログイン/サインアップの両方に利用でき、未登録ユーザーは自動作成、既存ユーザーは認証されます。

リクエスト:

  • Method: GET
  • Path: /auth/oauth/google
  • ヘッダー: なし
  • 認可: 不要

リクエストボディ:

フィールド必須説明
ボディなし-なし。設定はクエリパラメータで指定

クエリパラメータ:

フィールド必須説明
fpstring端末フィンガープリント
purposestringフロー目的:oauth-login または oauth-signup
redirectUrlstring完了後のリダイレクトURL
typeIdstringアイデンティティ種別ID(サインアップ時に必要)

レスポンス:

  • ステータス: 302 Found
  • ヘッダー: Google OAuth URL を含む Location

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

リクエスト例:

# OAuth Login
curl -v "{{host}}/auth/oauth/google?fp=device-fingerprint&purpose=oauth-login&redirectUrl=http://localhost/oauth/callback"

# OAuth Signup
curl -v "{{host}}/auth/oauth/google?fp=device-fingerprint&purpose=oauth-signup&redirectUrl=http://localhost/oauth/callback&typeId=001"

成功レスポンス:

HTTP/1.1 302 Found
Location: https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&response_type=code&redirect_uri=...&scope=email%20profile&state=...&client_id=...

エラーレスポンス:

必須パラメータが不足している場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"query parameter 'fp' is required",
"query parameter 'purpose' is required",
"query parameter 'redirectUrl' is required"
]
}
}

purpose が不正な値の場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Validation Error",
"data": [
"query parameter 'purpose' must be equal to one of the allowed values"
]
}
}

19. Google OAuth コールバック

Google OAuth のコールバックを処理し、認証フローを完了します。成功後は初回の OAuth リクエストで指定された redirectUrl にリダイレクトされ、認証トークン(ワンタイムまたはアクセストークン)が付与されます。

リクエスト:

  • Method: GET
  • Path: /auth/oauth/google/callback
  • ヘッダー: なし
  • 認可: 不要

リクエストボディ:

フィールド必須説明
ボディなし-なし。処理はクエリパラメータで行う

クエリパラメータ:

フィールド必須説明
codestringGoogle からのワンタイム認可コード(Passport.js により交換)
statestringフロー文脈を含む署名付きJWT(purpose, redirectUrl, typeId, fingerprint, userAgent)

レスポンス:

  • ステータス: 302 Found(最終遷移先へリダイレクト)
  • ヘッダー: 最終リダイレクトURLの Location

レスポンスボディ:

フィールド説明
ボディなし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: なし
  • ルートバリデーション: なし

リクエスト例:

curl -v "{{host}}/auth/oauth/google/callback?code=AUTH_CODE&state=STATE_TOKEN"

成功レスポンス:

HTTP/1.1 302 Found
Location: http://localhost:3000/oauth/callback?token=JWT_TOKEN

エラーレスポンス:

OAuth state が無効または期限切れの場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Invalid onetime token"
}
}

サインアップに typeId が必要な場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "typeId is required"
}
}

アイデンティティ作成に失敗した場合:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Failed to create identity"
}
}

該当するアイデンティティが見つからない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "No identity found for the given email."
}
}

DB操作に失敗した場合:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Error finding or creating identity"
}
}

🔒 セキュリティ機能

アカウント保護

  • ログイン失敗回数の追跡: 失敗回数を記録
  • アカウントロック: 規定回数(既定は5回、変更可)で自動ロック
  • パスワードハッシュ化: パスワードは安全にハッシュ化
  • トークンセキュリティ: デバイス指紋とIP検証を含む

トークン管理

  • アクセストークン: 短寿命のAPIアクセス用トークン
  • リフレッシュトークン: 再発行用の長寿命トークン
  • トークン検証: ドメイン・指紋・IP・UA を検証
  • セキュアクッキー: HTTP-only/secure で安全に保存

認証方法

ベアラートークン

// Use in Authorization header
Authorization: Bearer <access-token>

クッキー認証

// Tokens automatically sent with requests

⚙️ 設定オプション

サービス設定

interface AuthServiceConfig {
authSecrets?: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
maxFailedLoginAttempts?: number; // Default: 5
cookieOpts?: {
domain?: string;
maxAge?: string | number;
path?: string;
sameSite?: 'strict' | 'lax' | 'none';
};
jwtOpts?: {
jwtSignOptions?: SignOptions;
stateful?: boolean;
};
accessTokenExpireTime?: string; // Default: '2h'
onetimeTokenExpireTime?: string; // Default: '2h'
refreshTokenExpireTime?: string; // Default: '2d'
identity?: {
typeIds?: {
admin: string; // Admin user type identifier
guest: string; // Guest user type identifier
regular: string; // Regular user type identifier
};
};
verifyEmailConfig?: {
enabled: boolean; // Enable email verification feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
};
sender?: string; // Sender email address
};
invitation?: {
enabled: boolean; // Enable invitation feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
sender: string; // Sender email address
};
target?: string; // Token target for invitation validation
};
}

設定詳細

認証サービスの設定は、セキュリティ・クッキー・JWT・招待・メール確認の論理グループに整理されています。

🔐 セキュリティ設定

authSecrets - JWT トークンのセキュリティ用シークレット

  • : { authEncSecret: string; authSignSecret: string }
  • 説明: JWT の暗号化・署名に用いるシークレットキー
  • 既定: { authEncSecret: '', authSignSecret: '' }
  • 必須: 本番環境では必須
  • 子プロパティ:
    • authEncSecret: JWT ペイロード暗号化用のシークレット
    • authSignSecret: JWT 署名検証用のシークレット

maxFailedLoginAttempts - アカウントロックのしきい値

  • : number
  • 説明: ロックされるまでに許容されるログイン失敗回数の上限
  • 既定: 5
  • 挙動: しきい値超過でアカウントをロック(解除は手動)

🍪 クッキー設定

cookieOpts - HTTP クッキー設定

  • : { domain?: string; maxAge?: string | number; path?: string; sameSite?: 'strict' | 'lax' | 'none' }
  • 説明: 認証トークンのブラウザクッキーでの保存方法を制御
  • 既定: undefined(トークンの有効期限に準拠)
  • 子プロパティ:
    • domain: クッキーのドメイン範囲
      • : string
      • 説明: サブドメイン横断の範囲を制御
      • : '.example.com'(全サブドメイン)
    • maxAge: クッキーの有効期間
      • : string | number
      • 説明: 有効期間(ミリ秒)
    • path: クッキーのパス範囲
      • : string
      • 説明: 特定パスに限定
      • 既定: '/'(ドメイン全体)
      • : '/api'(API のみ)
    • sameSite: CSRF 保護レベル
      • : 'strict' | 'lax' | 'none'
      • 説明: クロスサイトリクエストでクッキーが送信される条件
      • :
        • 'strict': 同一サイトのみ送信(最も厳格)
        • 'lax': ナビゲーション時に送信(バランス)
        • 'none': すべてのクロスサイトで送信(secure: true 必須)

🔑 JWT 設定

jwtOpts - JWT 生成/検証オプション

  • : { jwtSignOptions?: SignOptions; stateful?: boolean }
  • 説明: JWT 署名/検証の挙動をカスタマイズ
  • 既定: undefined(標準設定)
  • 子プロパティ:
    • jwtSignOptions: JWT 署名設定
      • : SignOptions(jsonwebtoken)
      • 説明: 署名アルゴリズムやパラメータの調整
      • 既定: 標準署名
    • stateful: サーバー側トークン検証
      • : boolean
      • 説明: 失効管理などの強化のためサーバー側で検証
      • 既定: false(ステートレス)
      • 用途: トークン失効とセキュリティ強化

⏰ トークン有効期限

accessTokenExpireTime - アクセストークン寿命

  • : string(ms 形式)
  • 説明: API アクセス用の短寿命トークン
  • 既定: undefined
  • 形式: '30m', '1h', '2h' など(ms 形式)
  • セキュリティ: 露出時間を最小化

refreshTokenExpireTime - リフレッシュトークン寿命

  • : string(ms 形式)
  • 説明: 再発行用の長寿命トークン
  • 既定: undefined
  • 形式: '1d', '7d', '30d' など(ms 形式)
  • セキュリティ: HTTP-only/secure クッキーに保存

onetimeTokenExpireTime - ワンタイムトークン寿命

  • : string(ms 形式)
  • 説明: パスワード再設定・メール確認用の一時トークン
  • 既定: undefined
  • 形式: '15m', '1h', '2h' など(ms 形式)
  • セキュリティ: 1回限り・短寿命

📧 メール確認設定

verifyEmailConfig - メール確認の設定

  • : { enabled: boolean; emailConfig?: EmailConfig; mailService?: MailService; sender: string }
  • 説明: メール確認機能とテンプレートを制御
  • 既定: undefined(メール確認は無効)
  • 子プロパティ:
    • enabled: メール確認機能を有効化
      • : boolean
      • 説明: メール確認機能のマスタースイッチ
      • 既定: false
      • 必須: メール確認を使用する場合は必須
    • emailConfig: メールテンプレート設定
      • : { bodyTemplate: string; subject: string; urlTemplate: string }
      • 説明: 確認メールのテンプレート
      • 必須: enabled の場合に必須
      • 子プロパティ:
        • bodyTemplate: HTML メール本文テンプレート
          • : string
          • 説明: 本文の HTML テンプレート。{{url}}, {{email}}, {{token}} を使用可能。url には urlTemplate の値を適用
          • : "Hello {{email}}, click <a href=\"{{url}}\">here</a> to verify your email."
        • subject: メール件名
          • : string
          • 説明: 確認メールの件名
          • : "Verify your email address"
        • urlTemplate: 確認リンクの URL テンプレート
    • sender: 送信者メールアドレス
      • : string
      • 説明: 確認メールの送信元アドレス
      • 必須: いいえ(任意)
      • : "noreply@yourapp.com"
ステータスエラーメッセージ説明
400Validation Errorリクエストボディの形式が不正
400verification email feature not enabledメール確認が未設定
400verification email feature requires a mail service to be providedメール送信サービスが未設定
400verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplateメール設定が不足
400Unable to verify token確認トークンを検証できない
401wrong credentials providedメール/パスワードが不正
401This account is locked失敗回数超過によりロック済み
401Token is not valid access token無効または期限切れのトークン
401Token fails security checkトークンのセキュリティ検証に失敗
401token could not be verified認可トークンがない/無効
403token does not contain expected dataトークンの内容が期待値に一致しない
403User is not authorized to access this resource権限不足(管理者アクセスが必要)
404User not foundユーザーが存在しない
404Invitation not found招待が存在しない
409Email already verified or no changes madeメールは既に確認済み
422unable to register "email"メールアドレスは既に存在
500unable to generate access tokenアクセストークンの生成に失敗
500unable to generate refresh tokenリフレッシュトークンの生成に失敗
500Failed to send verification email確認メールの送信に失敗
400/500Failed to create invitation招待の作成に失敗

サービスオプション(第3引数)

interface AuthServiceOptions {
mailService?: MailService; // Mail service implementation
googleOAuthDriver?: GoogleOAuthDriver; // Google OAuth driver instance
}

これらは authService(dataStores, config, options) の第3引数で指定します。

📨 招待設定

invitation - 招待機能の設定

  • : { enabled: boolean; emailConfig?: InvitationEmailConfig; target: string }
  • 説明: 招待機能とメールテンプレートを制御
  • 既定: undefined(無効)
  • 子プロパティ:
    • enabled: 招待機能を有効化
      • : boolean
      • 説明: 招待機能のマスタースイッチ
      • 既定: false
      • 必須: 招待機能を使用する場合は必須
    • emailConfig: 招待メールのテンプレート設定
      • : { bodyTemplate: string; subject: string; urlTemplate: string; sender: string }
      • 説明: 招待メールのテンプレート
      • 必須: enabled の場合に必須
      • 子プロパティ:
        • bodyTemplate: HTML メール本文テンプレート
          • : string
          • 説明: 本文の HTML テンプレート。{{url}}, {{token}}, {{email}} を使用可能。url には urlTemplate の値を適用
          • : "<h1>You're invited!</h1><p>Click <a href='{{url}}'>here</a> to accept the invitation.</p>"
        • subject: メール件名
          • : string
          • 説明: 招待メールの件名
          • : "You're invited to join our organization"
        • urlTemplate: 招待リンクの URL テンプレート
          • : string
          • 説明: {{token}}{{email}} プレースホルダを含む URL テンプレート
          • : "https://yourapp.com/invitations/accept?token={{token}}&email={{email}}"
        • sender: 送信者メールアドレス
          • : string
          • 説明: 招待メールの送信元アドレス
          • 必須: enabled の場合に必須
          • : "invites@yourapp.com"
    • target: 招待検証用トークンのターゲット
      • : string
      • 説明: 招待トークン検証のターゲット識別子
      • 既定: "invitation"
      • 必須: いいえ
      • : "invitation"

設定例

const authConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
maxFailedLoginAttempts: 3,
cookieOpts: {
secure: true,
sameSite: 'strict',
maxAge: 2 * 24 * 60 * 60 * 1000 // 2 days
},
accessTokenExpireTime: '1h',
refreshTokenExpireTime: '7d',
onetimeTokenExpireTime: '30m',
verifyEmailConfig: {
enabled: true,
emailConfig: {
bodyTemplate: 'Hello {{email}}, click <a href="{{url}}">here</a> to verify your email address.',
subject: 'Verify your email address',
urlTemplate: 'https://yourapp.com/verify?token={{token}}'
},
sender: 'noreply@yourapp.com'
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="{{url}}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token={{token}}&email={{email}}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
};

🚨 エラーハンドリング

認証関連のエラーは、適切なHTTPステータスコードとJSON形式で返されます。

代表的なエラーコード

ステータスエラーメッセージ説明
400Validation ErrorInvalid request body format
400verification email feature not enabledEmail verification not configured
400verification email feature requires a mail service to be providedMail service not configured
400verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplateMissing email configuration
400Unable to verify tokenInvalid verification token
401wrong credentials providedInvalid email/password
401This account is lockedAccount locked due to failed attempts
401Token is not valid access tokenInvalid or expired token
401Token fails security checkToken security validation failed
401token could not be verifiedMissing or invalid authorization token
403token does not contain expected dataToken validation failed
403User is not authorized to access this resourceUser lacks required permissions (admin access)
404User not foundUser does not exist
404Invitation not foundInvitation does not exist
409Email already verified or no changes madeEmail already verified
422unable to register "email"Email already exists
500unable to generate access tokenToken generation failed
500unable to generate refresh tokenRefresh token generation failed
500Failed to send verification emailEmail sending process failed
400/500Failed to create invitationInvitation creation failed

エラーレスポンス形式

{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}

🔗 関連ドキュメント