Authentication Flow
Relevant source files
The following files were used as context for generating this wiki page:
- marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts
- marketplace-backend/app/src/middlewares/add-auth-header.middleware.ts
- marketplace-frontend/src/app/services/root/authorization.service.ts
- marketplace-backend/app/src/modules/auth/auth.module.ts
- marketplace-backend/app/src/repositories/impl/customers.repository.ts
- marketplace-backend/app/src/main.ts
The Authentication Flow manages user identity and access control across the marketplace application. This system utilizes JSON Web Tokens (JWT) stored in secure cookies to authenticate requests between the Angular frontend and the NestJS backend.
System Overview
The authentication architecture relies on a decoupled structure where the backend handles credential validation and token generation, while the frontend manages session state and request interception.
Core Authentication Components
| Component | Responsibility |
|---|---|
AuthController | Handles login, registration, logout, and account info retrieval. |
AuthorizationService | Manages frontend HTTP requests for auth operations and session state. |
AddAuthHeaderMiddleware | Extracts JWT from cookies and attaches it to the Authorization header. |
CustomersRepository | Performs database operations for user credentials and profiles. |
JwtStrategy | Validates JWT payloads for protected routes. |
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts, marketplace-frontend/src/app/services/root/authorization.service.ts, marketplace-backend/app/src/middlewares/add-auth-header.middleware.ts
Login and Registration Flow
When a user submits credentials, the system validates the data against the database. If successful, the backend generates a JWT and sets it as a secure cookie.
Sequence of Authentication
The following diagram illustrates the interaction between the Frontend Service, the Auth Controller, and the Database during a login attempt.
Registration Logic
During registration, the CustomersRepository performs the following steps:
- Generates a unique UUID for the user.
- Hashes the password using
bcryptwith a salt round of 10. - Assigns the
Defaultuser role. - Persists the record to MongoDB via the
Customerschema.
Sources: marketplace-backend/app/src/repositories/impl/customers.repository.ts:22-33, marketplace-backend/app/src/schemas/customer.schema.ts
Session Management
The system maintains sessions using a combination of HTTP-only cookies and server-side caching.
Server-Side Middleware
The addAuthHeader middleware processes every incoming request. If a refresh token cookie exists, the middleware automatically appends a Bearer token to the Authorization header.
export function addAuthHeader(req: Request, res: Response, next: Function) {
const {REFRESH_TOKEN_COOKIE, BEARER} = process.env;
const {headers, cookies} = req;
const tokenFromRequestCookies: string = cookies[REFRESH_TOKEN_COOKIE];
if (tokenFromRequestCookies) {
headers.authorization = `${BEARER} ${cookies[REFRESH_TOKEN_COOKIE]}`;
}
next();
}
Sources: marketplace-backend/app/src/middlewares/add-auth-header.middleware.ts:4-15
Caching Strategy
The backend uses a cache manager to store CustomerDto objects. This reduces database load when retrieving account information for authenticated users. The cache key follows the format id_{customerId}.
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:13-52
API Endpoints
The AuthController exposes the following endpoints under the /api/v1/auth prefix:
| Endpoint | Method | Description |
|---|---|---|
/account | GET | Retrieves current customer info using the JWT in cookies. |
/register | POST | Creates a new user and returns a JWT cookie. |
/login | POST | Validates credentials and returns a JWT cookie. |
/logout | POST | Clears the JWT cookie and removes user data from cache. |
Sources: marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:24-81
Security Configuration
The application implements several security measures:
- CORS: Configured in
main.tsto allow credentials (cookies) and expose theSet-Cookieheader. - HTTP-Only Cookies: JWTs are stored in cookies with the
httpOnlyflag to prevent XSS-based token theft. - Password Hashing: Utilizes
bcryptfor secure storage of user secrets. - JWT Verification: The
JwtModuleis configured with a secret key and expiration time defined in environment variables.
Sources: marketplace-backend/app/src/main.ts:24-28, marketplace-backend/app/src/modules/auth/auth.module.ts:21-26, marketplace-backend/app/src/modules/auth/controllers/auth.controller.ts:14-19
The Authentication Flow ensures that user identity is consistently verified across the platform while maintaining a seamless experience through automated token handling and server-side caching.