Skip to content

Auth Services

The Auth Module provides two key services that form the backbone of authentication flows:

AuthService → Core service for authenticating users using pluggable strategies.
JWTService → Utility for issuing and verifying JWT tokens securely.

These services are designed to be modular, extensible, and easy to integrate into your application.


The AuthService is the main entry point for handling authentication logic.

  • Authenticate users via pluggable strategies (e.g., local username/password, Google, GitHub, etc.).
  • Decouple the application layer from the specific implementation details of each strategy.
  • Provide a unified interface for login and validation.
password-auth.strategy.ts
import { AuthStrategy } from '@domusjs/auth';
interface PasswordAuthPayload {
email: string;
password: string;
}
interface PasswordAuthResult {
userId: string;
email: string;
}
export class PasswordAuthStrategy implements AuthStrategy<PasswordAuthPayload, PasswordAuthResult> {
async login(payload: PasswordAuthPayload): Promise<PasswordAuthResult> {
// Validate user, check password, etc.
return { userId: 'abc123', email: payload.email };
}
}

2. Register Auth Module with custom strategies

Section titled “2. Register Auth Module with custom strategies”
import { registerAuthModule, AuthService } from '@domusjs/auth';
import { PasswordAuthStrategy } from './password-auth.strategy';
const jwtOptions = {
secret: 'my_jwt_secret',
expiresIn: '1h',
};
registerAuthModule(
[
{
strategy: PasswordAuthStrategy,
instance: new PasswordAuthStrategy(),
},
],
jwtOptions
);
import { container } from 'tsyringe';
import { AuthService } from '@domusjs/auth';
import { PasswordAuthStrategy } from './password-auth.strategy';
const authService = container.resolve<AuthService>('AuthService');
const authResult = await authService.loginWith(PasswordAuthStrategy, {
email: 'me@test.com',
password: '1234',
});

The JWTService wraps the popular jsonwebtoken library and provides:

  • Token signing → Create JWTs for authenticated users.
  • Token verification → Validate incoming tokens in requests.
import { container } from 'tsyringe';
import { JWTService } from '@domusjs/auth';
const jwtService = container.resolve<JWTService>('JWTService');
const token = jwtService.sign({ userId: '123' });
const payload = jwtService.verify(token);

✅ This service is used internally by the JWT Passport strategy and can also be used in your custom flows.


The jwtAuthMiddleware is a ready-to-use Express middleware provided by DomusJS to protect your routes using JWT authentication.

  • Verifies the JWT from the Authorization header.
  • Attaches the authenticated user (if valid) to the req.auth object.
  • Throws a 401 Unauthorized error if the token is missing or invalid.
import { jwtAuthMiddleware, AuthenticatedRequest } from '@domusjs/auth';
interface AuthUserResult {
userId: string;
email: string;
}
app.get('/protected', jwtAuthMiddleware<AuthUserResult>(), (req, res) => {
const { auth } = req as AuthenticatedRequest<AuthUserResult>;
res.json({
message: 'This is a protected route',
userId: auth.userId,
email: auth.email,
});
});

✅ Use it to secure routes that require authenticated access.

Note: When you use jwtAuthMiddleware, the middleware enriches the Express Request object with an auth property that contains the decoded authenticated user payload. To access it safely with TypeScript, you can cast the request using the AuthenticatedRequest<T> type.

Make sure that the JWT payload has been previously signed using the same contract (AuthUserResult) so that the middleware can correctly parse and type the auth data on the request. This ensures type consistency between the payload you issue (JWTService.sign()) and the payload you consume (AuthenticatedRequest).


✅ Use the AuthService as the single point of authentication in your app.
✅ Leverage the JWTService for stateless, scalable token-based auth.
✅ Keep strategy logic decoupled to make swapping or adding methods easy.
✅ Always store secrets and keys securely (e.g., environment variables).