๐ 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 collection; 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, 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},
),
);
| Configuration | Default from getMergedAuthConfig() | Effect |
|---|---|---|
authMode | Omitted โ Bearer mode | Cookie 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. |
maxFailedLoginAttempts | 5 | Credential-login failure threshold. |
mfaCodeLength | 6 | Generated MFA-code length. |
isMfaEnabled | false | Selects the MFA branch of credential login. |
verifyEmailConfig.enabled | false | Controls 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โ
| Task | Start with | Contract |
|---|---|---|
| Register and sign in | registerCredentialsFeature, loginWithCredentialsFeature | Features, routes |
| Use an access token | Bearer Authorization header | Validators, auth utility |
| Use cookies | authMode: 'cookie' and cookie-parser | Cookie utility |
| Add MFA or passwordless login | MFA and one-time-token features | Features, blocks |
| Build a custom service | Compose exported features | Composite 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.
Cookie HTTP workflowโ
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, 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โ
| Page | Purpose |
|---|---|
| Blocks | Reusable identity, token, email, MFA, and error contracts. |
| Features | Schema/route compositions. |
| Handlers | Route-pipeline operations and terminators. |
| Routes | Endpoint, status, access, and pipeline contracts. |
| Schemas | Input locations and validation contracts. |
| Validators | Authentication and authorization composition. |
Related modulesโ
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.