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

🔐 Authentication

Authentication provides credential registration, JWT sessions, MFA, one-time-token flows, email verification, password recovery, and identity activation through authService.

Start here

For a normal application, mount the service instead of assembling route handlers yourself. The source requires an identities and refreshtokens collections; onetimetokens is needed by token, reset, verification, and MFA flows, while invitations, mail, and OAuth drivers are required only by the corresponding features.

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()); // Required only when authMode is '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},
),
);
ConfigurationDefault from getMergedAuthConfig()Effect
authModeOmitted → Bearer modeCookie mode selects getCookieTokenInfo; otherwise the service selects getBearerTokenInfo.
accessTokenSignOptions.expiresIn'15m'Access-token lifetime.
refreshTokenSignOptions.expiresIn'2d'Refresh-token lifetime.
onetimeTokenSignOptions.expiresIn'5m'One-time-token lifetime.
maxFailedLoginAttempts5Credential-login failure threshold.
mfaCodeLength6Generated MFA-code length.
isMfaEnabledfalseSelects the MFA branch of credential login.
verifyEmailConfig.enabledfalseControls verification-email behavior in the handler flow.

cookieOpts overrides cookie attributes but does not activate cookie authentication; use authMode: 'cookie'. Cookie mode still requires host-installed cookie-parser.

View service composition source
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,
}]
)
);
};

Common tasks

TaskStart withContract
Register and sign inregisterCredentialsFeature, loginWithCredentialsFeatureFeatures, routes
Use an access tokenBearer Authorization headerValidators, auth utility
Use cookiesauthMode: 'cookie' and cookie-parserCookie utility
Add MFA or passwordless loginMFA and one-time-token featuresFeatures, blocks
Build a custom serviceCompose exported featuresComposite service how-to

Bearer HTTP workflow

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"

The matching contracts are registerCredentialsSchema, loginWithCredentialsSchema, checkTokenSchema, and deleteRefreshTokensRoute. checkTokenRoute validates the body token and does not use an Authorization header; deleteRefreshTokensRoute does require an authenticated administrator or the matching identity.

Set authMode: 'cookie', register cookie-parser before authService, and let curl retain the cookies set by login:

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-mode login returns {id} and sets session cookies. Cookie-mode refresh and logout use their empty-body schemas and return the route’s cookie-mode response; see refreshTokenCookieSchema and logoutCookieSchema.

Custom feature composition

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);

Compose this inside a service that supplies the same datastore, configuration, and authentication context as authService; the composite-service guide shows the complete host setup.

Reference map

PagePurpose
BlocksReusable identity, token, email, MFA, and error contracts.
FeaturesSchema/route compositions.
HandlersRoute-pipeline operations and terminators.
RoutesEndpoint, status, access, and pipeline contracts.
SchemasInput locations and validation contracts.
ValidatorsAuthentication and authorization composition.

Use mail-service drivers for email flows and OAuth drivers for provider flows. authService always composes the Invitation and OAuth features; provide their corresponding collections and drivers before invoking those routes. See error handling for application-level failures.