🔐 認証 (Authentication)
認証機能は、authService を通じて、クレデンシャル登録、JWT セッション、MFA、ワンタイムトークンフロー、メール検証、パスワードリカバリー、アイデンティティアクティベーションを提供します。
まずはここから
通常のアプリケーションでは、ルートハンドラを自分で組み立てる代わりに、サービスを取り付けます。ソースには identities と refreshtokens コレクションが必要で、onetimetokens はトークン、リセット、検証、MFA フローに必要であり、invitations、メール、OAuth ドライバーは対応する機能のみで必要です。
import express from 'express';
import cookieParser from 'cookie-parser';
import {services} from '@nodeblocks/backend-sdk';
const app = express();
app.use(express.json());
app.use(cookieParser()); // authMode が 'cookie' の場合のみ必須。
app.use(
'/api',
services.authService(
{identities, refreshtokens, onetimetokens},
{
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET!,
authSignSecret: process.env.AUTH_SIGN_SECRET!,
},
authMode: 'bearer',
accessTokenSignOptions: {expiresIn: '15m'},
refreshTokenSignOptions: {expiresIn: '2d'},
onetimeTokenSignOptions: {expiresIn: '5m'},
},
{mailService},
),
);
| 設定 | getMergedAuthConfig() からデフォルト | 効果 |
|---|---|---|
authMode | Omitted → Bearer モード | Cookie モードは getCookieTokenInfo を選択し、それ以外の場合はサービスが getBearerTokenInfo を選択します。 |
accessTokenSignOptions.expiresIn | '15m' | アクセストークンの有効期限。 |
refreshTokenSignOptions.expiresIn | '2d' | リフレッシュトークンの有効期限。 |
onetimeTokenSignOptions.expiresIn | '5m' | ワンタイムトークンの有効期限。 |
maxFailedLoginAttempts | 5 | クレデンシャルログイン失敗のしきい値。 |
mfaCodeLength | 6 | 生成される MFA コードの長さ。 |
isMfaEnabled | false | クレデンシャルログインの MFA ブランチを選択します。 |
verifyEmailConfig.enabled | false | ハンドラフロー内の検証メール動作を制御します。 |
cookieOpts はクッキー属性を上書きしますが、クッキー認証を有効にはしません;authMode: 'cookie' を使用してください。Cookie モードでも cookie-parser のホストインストールが必要です。
サービス構成ソースを表示
export const authService: AuthenticationService = (
dataStores,
configuration: Partial<AuthenticationServiceConfiguration> = {},
{ mailService, googleOAuthDriver, twitterOAuthDriver, lineOAuthDriver } = {}
) => {
const mergedConfiguration = getMergedAuthConfig(configuration);
return defService(
partial(
compose(
registerCredentialsFeature, loginWithCredentialsFeature, logoutFeature,
loginWithOnetimeTokenFeature, emailVerificationFeature, confirmEmailFeature,
createInvitationFeature, findInvitationsFeature, getInvitationFeature,
deleteInvitationFeature, changeEmailFeature, checkTokenFeature,
confirmNewEmailFeature, sendResetPasswordLinkEmailFeature,
completePasswordResetFeature, changePasswordFeature, deactivateFeature,
activateFeature, googleOAuthFeature, googleOAuthCallbackFeature,
refreshTokenFeature, deleteRefreshTokensFeature, resendMfaCodeFeature,
verifyMfaCodeFeature, twitterOAuthFeature, twitterOAuthCallbackFeature,
lineOAuthFeature, lineOAuthCallbackFeature
),
[{
authenticate: configuration.authMode === 'cookie'
? getCookieTokenInfo
: getBearerTokenInfo,
configuration: mergedConfiguration,
dataStores, googleOAuthDriver, lineOAuthDriver, mailService, twitterOAuthDriver,
}]
)
);
};
一般的なタスク
| タスク | 開始点 | 契約 |
|---|---|---|
| 登録とサインイン | registerCredentialsFeature, loginWithCredentialsFeature | Features, routes |
| アクセストークンの使用 | Bearer Authorization ヘッダー | Validators, auth utility |
| クッキーの使用 | authMode: 'cookie' と cookie-parser | Cookie utility |
| MFA またはパスワードレスログインの追加 | MFA およびワンタイムトークン機能 | Features, blocks |
| カスタムサービスの構築 | エクスポートされた機能を構成する | Composite service how-to |
Bearer HTTP ワークフロー
API_BASE_URL='http://localhost:8080/api'
IDENTITY_ID='replace-with-an-identity-id'
ACCESS_TOKEN='replace-with-an-access-token-returned-by-login'
curl -X POST "$API_BASE_URL/auth/register" \
-H 'content-type: application/json' \
-d '{"email":"ada@example.com","password":"correct-horse-battery-staple"}'
curl -X POST "$API_BASE_URL/auth/login" \
-H 'content-type: application/json' \
-d '{"email":"ada@example.com","password":"correct-horse-battery-staple"}'
curl -X POST "$API_BASE_URL/auth/token/check" \
-H 'content-type: application/json' \
-d "{\"token\":\"$ACCESS_TOKEN\"}"
# A protected route: administrators or the matching identity may revoke refresh tokens.
curl -X DELETE "$API_BASE_URL/auth/$IDENTITY_ID/refresh-tokens" \
-H "authorization: Bearer $ACCESS_TOKEN"
対応する契約は registerCredentialsSchema, loginWithCredentialsSchema, checkTokenSchema, および deleteRefreshTokensRoute です。checkTokenRoute はボディトークンを検証し、Authorization ヘッダーを使用しません;deleteRefreshTokensRoute は認証された管理者または対応するアイデンティティが必要です。
Cookie HTTP ワークフロー
authMode: 'cookie' を設定し、authService 前に cookie-parser を登録し、ログインで設定されたクッキーを curl が保持するようにします:
curl -c cookies.txt -X POST http://localhost:8080/api/auth/login \
-H 'content-type: application/json' \
-d '{"email":"ada@example.com","password":"correct-horse-battery-staple"}'
curl -b cookies.txt -X POST http://localhost:8080/api/auth/token/refresh \
-H 'content-type: application/json' -d '{}'
curl -b cookies.txt -X POST http://localhost:8080/api/auth/logout \
-H 'content-type: application/json' -d '{}'
Cookie モードのログインは {id} を返し、セッションクッキーを設定します。Cookie モードのリフレッシュとログアウトは空ボディスキーマを使用し、ルート対応するクッキーモード応答を返します;refreshTokenCookieSchema および logoutCookieSchema を参照してください。
カスタム機能構成
import {partial} from 'ramda';
import {features, primitives, utils} from '@nodeblocks/backend-sdk';
const authenticationFeatureComposer = primitives.compose(
features.registerCredentialsFeature,
features.loginWithCredentialsFeature,
features.logoutFeature,
);
const authenticationRouter = primitives.defService(partial(authenticationFeatureComposer, [{
authenticate: utils.getBearerTokenInfo,
configuration: {authSecrets},
dataStores: {identities, refreshtokens, onetimetokens},
}]));
app.use('/api', authenticationRouter);
この構成は、authService と同じデータストア、設定、認証コンテキストを供給するサービス内で実行してください;composite-service guide は完全なホストセットアップを示しています。
リファレンスマップ
| ページ | 目的 |
|---|---|
| Blocks | 再利用可能なアイデンティティ、トークン、メール、MFA、エラー契約。 |
| Features | スキーマ/ルート構成。 |
| Handlers | ルートパイプライン操作とターミネーター。 |
| Routes | エンドポイント、ステータス、アクセス、パイプライン契約。 |
| Schemas | 入力位置と検証契約。 |
| Validators | 認証と認可構成。 |
関連モジュール
メールフローには mail-service drivers、プロバイダーフローには OAuth drivers を使用してください。authService は常に Invitation および OAuth 機能を構成します;それらのルートを実行する前に、対応するコレクションとドライバーを提供してください。アプリケーションレベルの失敗については error handling を参照してください。