Skip to main content
The Medical Appointments API uses JWT (JSON Web Token) based authentication to secure endpoints and manage user sessions.

How Authentication Works

The authentication system follows a token-based approach:
1

Register or Login

You obtain a JWT token by either registering a new account or logging in with existing credentials.
2

Store the Token

The server returns a JWT token that you must store securely in your application.
3

Include in Requests

For protected endpoints, include the token in the Authorization header of your requests.
4

Token Validation

The server validates the token on each request and grants access if valid.

Authentication Flow

Token Lifecycle

Token Generation

When you successfully log in, the system generates a JWT token containing:
  • User ID: Unique identifier for the authenticated user
  • Role: User role (PATIENT, DOCTOR, or ADMIN)
  • Expiration: Token validity period (1 hour)
The token is signed using a secret key (configured via JWT_SECRET environment variable) to prevent tampering.

Token Validation

The authentication middleware (src/middlewares/auth.js:3-17) validates tokens on protected routes:
  1. Extracts the token from the Authorization header
  2. Verifies the token signature using the secret key
  3. Checks if the token has expired
  4. Attaches user information to the request object

Token Expiration

Tokens expire after 1 hour of issuance. After expiration, you must login again to obtain a new token.
Currently, the API does not support token refresh. When your token expires, you will receive a 403 Forbidden error and need to re-authenticate.

Security Considerations

Password Hashing

All passwords are hashed using bcryptjs with a configurable salt rounds value (default: 10 rounds). Passwords are never stored in plain text.
// From src/services/authService.js:15
const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);

Password Requirements

Passwords must be at least 8 characters long. This is enforced both at the schema validation level and in the service layer.

Token Storage

Client-Side Security: Never store JWT tokens in localStorage if your application is vulnerable to XSS attacks. Consider using httpOnly cookies or secure storage mechanisms.

HTTPS Requirement

Always use HTTPS in production to prevent token interception during transmission.

Protected Routes

Routes that require authentication use the authenticateToken middleware. Example from src/routes/auth.js:10-12:
router.get('/protected-route', authenticateToken, (req, res) => {
    res.send('Esta es una ruta protegida, acceso permitido para el usuario autenticado.');
});

Error Responses

The authentication system returns specific error messages:
Status CodeError MessageDescription
401Access Denied, no token providedNo token in Authorization header
403Invalid tokenToken is malformed, expired, or has invalid signature
401Usuario y/o contraseña incorrectaInvalid login credentials
400Various validation errorsMissing fields or invalid data format

Next Steps

Register a User

Learn how to create a new user account

Login

Authenticate and receive a JWT token

JWT Tokens

Understand token structure and usage

Build docs developers (and LLMs) love