Skip to main content

Authentication Service

The Authentication Service provides secure user authentication and authorization capabilities across your organization’s ecosystem. It manages user identity verification, session handling, and supports multiple authentication methods including password, one-time passwords (OTP), OAuth providers (Google, Microsoft), Azure AD, OAuth, and SAML SSO.

Base URL

All endpoints are prefixed with /api/v1

Authentication

Most endpoints require authentication via Bearer token:
Authorization: Bearer YOUR_TOKEN
Internal endpoints use scoped token authentication for service-to-service communication with specific scopes:
  • PASSWORD_RESET - For password reset operations
  • TOKEN_REFRESH - For token refresh operations
  • FETCH_CONFIG - For configuration updates

Architecture Overview

The Authentication Service is built on a Node.js backend with MongoDB for data persistence and Redis for session management. The service implements a container-based dependency injection pattern using InversifyJS for better modularity and testability. Key components that the Auth Service integrates with:
  • IAM Service - Manages user and organization information
  • Configuration Manager - Stores authentication provider configurations
  • Communication Service - Handles email delivery for password resets and OTP
  • Redis - Manages authentication sessions and temporary tokens

Authentication Flow Process

The Auth Service employs a multi-step session-based authentication flow:
  1. Authentication Initialization
    • Client calls the /userAccount/initAuth endpoint with an email
    • Server validates the email and creates a temporary session in Redis
    • Server returns a session token in the x-session-token response header along with available authentication methods
  2. Authentication Steps
    • Client calls /userAccount/authenticate with the session token in the x-session-token header
    • Client provides chosen authentication method and credentials
    • If multi-factor authentication is configured, the server returns information about the next step
    • Client repeats the authentication step with appropriate credentials until all required steps are completed
  3. Token Issuance
    • After successful authentication, the server issues access and refresh tokens
    • The Redis session is cleared
    • Client stores tokens for subsequent API calls
Here’s a sequence diagram of the flow:

Data Models

interface IOrgAuthConfig extends Document {
  orgId: Types.ObjectId;
  domain?: string;
  authSteps: {
    order: number;
    allowedMethods: {
      type: 'samlSso' | 'otp' | 'password' | 'google' | 'microsoft' | 'azureAd' | 'oauth';
    }[];
  }[];
  isDeleted?: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}
interface IUserCredentials extends Document {
  userId?: string | null;
  orgId: string;
  ipAddress: string;
  otpValidity?: number;
  hashedOTP?: string;
  hashedPassword?: string;
  forceNewPasswordGeneration: boolean;
  wrongCredentialCount: number;
  isBlocked: boolean;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}
interface IUserActivity extends Document {
  email: string;
  userId: Types.ObjectId;
  orgId?: Types.ObjectId;
  activityType:
    | 'LOGIN'
    | 'LOGOUT'
    | 'LOGIN_ATTEMPT'
    | 'OTP_GENERATE'
    | 'WRONG_OTP'
    | 'WRONG_PASSWORD'
    | 'REFRESH_TOKEN';
  loginMode?:
    | 'OTP'
    | 'PASSWORD'
    | 'AUTH SERVICE'
    | 'GOOGLE OAUTH'
    | 'MICROSOFT OAUTH'
    | 'AZUREAD OAUTH'
    | 'OAUTH'
    | 'SSO';
  ipAddress: string;
  isDeleted?: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}
interface SessionData {
  token?: string;
  userId: string;
  email: string;
  orgId: string;
  authConfig: IAuthStep[];
  currentStep: number;
  isAuthenticated?: boolean;
  [key: string]: any; // Allows additional properties
}

Session Management with Redis

The Auth Service uses Redis to store temporary session data during the authentication process:
  • Sessions are identified by a unique UUID token
  • The x-session-token header is used to track the session across requests
  • Sessions expire after a configurable period (default: 1 hour)
  • Session data includes authentication state, user info, and available auth methods
  • After successful authentication, sessions are deleted from Redis

Token-Based Authentication

After successful authentication, the service issues two types of JWTs:
  1. Access Token
    • Short-lived token (typically 1 hour)
    • Contains user ID, organization ID, user email, and permissions
    • Used for authorizing API requests across services
  2. Refresh Token
    • Longer-lived token (typically 7 days)
    • Used to obtain new access tokens when they expire
    • Prevents the need for frequent re-authentication
Both tokens are cryptographically signed with JWT secrets to ensure authenticity.

API Endpoints

Core authentication endpoints for initializing and completing the authentication process.
Start the authentication process for a user.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/initAuthRequest Body Parameters:
ParameterTypeRequiredDescription
emailstringYesThe user’s email address
{
  "email": "user@example.com"
}
Perform authentication with credentials for a specific method.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/authenticateHeaders:
HeaderValueRequiredDescription
x-session-tokenstringYesSession token obtained from the initAuth response headers
Request Body Parameters:
ParameterTypeRequiredDescription
methodstringYesAuthentication method (password, otp, google, microsoft, azureAd, oauth, samlSso)
credentialsobjectYesCredentials object for the specified method
Authentication Methods:
Password Authentication
{
  "method": "password",
  "credentials": {
    "password": "your-secure-password"
  }
}
OTP Authentication
{
  "method": "otp",
  "credentials": {
    "otp": "123456"
  }
}
Google Authentication
{
  "method": "google",
  "credentials": "google-id-token-string"
}
Microsoft Authentication
{
  "method": "microsoft",
  "credentials": {
    "accessToken": "microsoft-access-token",
    "idToken": "microsoft-id-token"
  }
}
Azure AD Authentication
{
  "method": "azureAd",
  "credentials": {
    "accessToken": "azure-ad-access-token",
    "idToken": "azure-ad-id-token"
  }
}
OAuth Authentication
{
  "method": "oauth",
  "credentials": {
    "accessToken": "oauth-access-token",
    "idToken": "oauth-id-token"
  }
}
One-time password generation and validation.
Generate and send an OTP to the user’s email.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/login/otp/generateRequest Body Parameters:
ParameterTypeRequiredDescription
emailstringYesThe user’s email address (must be valid email format)
Validation:
  • Email must be in valid email format
  • Request goes through ValidationMiddleware with email validation
{
  "email": "user@example.com"
}
OAuth token exchange and provider integration.
Exchange OAuth authorization code for tokens.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/oauth/exchangeRequest Body Parameters:
ParameterTypeRequiredDescription
codestringYesAuthorization code from OAuth provider
emailstringYesUser’s email address
providerstringYesOAuth provider name
redirectUristringYesRedirect URI used in OAuth flow
{
  "code": "authorization-code-from-provider",
  "email": "user@example.com",
  "provider": "google",
  "redirectUri": "https://your-app.com/callback"
}
Password reset, change, and recovery operations.
Initiate password reset process via email.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/password/forgotRequest Body Parameters:
ParameterTypeRequiredDescription
emailstringYesThe user’s email address
{
  "email": "user@example.com"
}
Reset password using token from email.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/password/reset/tokenHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesPassword reset token from email (uses PASSWORD_RESET scope)
Request Body Parameters:
ParameterTypeRequiredDescription
passwordstringYesNew password (must meet complexity requirements)
{
  "password": "new-secure-password"
}
Change password for authenticated user.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/password/resetHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid access token (requires user authentication)
Request Body Parameters:
ParameterTypeRequiredDescription
currentPasswordstringYesCurrent password
newPasswordstringYesNew password (must meet complexity requirements)
{
  "currentPassword": "current-password",
  "newPassword": "new-secure-password"
}
Token refresh and session management operations.
Refresh access token using refresh token.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/refresh/tokenHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid refresh token (uses TOKEN_REFRESH scope)
Request Body Parameters: No body parameters required.
Logout user and invalidate session.
  • Request
  • Response
Endpoint: POST /api/v1/userAccount/logout/manualHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid access token (requires user authentication)
Request Body Parameters: No body parameters required.
SAML Single Sign-On authentication and configuration.
Initiate SAML authentication flow.
  • Request
  • Response
Endpoint: GET /api/v1/saml/signInQuery Parameters:
ParameterTypeRequiredDescription
emailstringYesThe user’s email address
sessionTokenstringYesSession token from init authentication
GET /api/v1/saml/signIn?email=user@example.com&sessionToken=session-token-123
Handle SAML authentication response from Identity Provider.
  • Request
  • Response
Endpoint: POST /api/v1/saml/signIn/callbackThis endpoint is called by the Identity Provider after successful authentication. No manual parameters needed as this is part of the SAML flow.
Update SAML application configuration.
  • Request
  • Response
Endpoint: POST /api/v1/saml/updateAppConfigHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid scoped token with FETCH_CONFIG scope
Manage organization-wide authentication settings and methods.
Retrieve current authentication methods configuration.
  • Request
  • Response
Endpoint: GET /api/v1/orgAuthConfig/authMethodsHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid admin access token
Update organization authentication methods configuration.
  • Request
  • Response
Endpoint: POST /api/v1/orgAuthConfig/updateAuthMethodHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid admin access token
Request Body Parameters:
ParameterTypeRequiredDescription
authMethodarrayYesArray of authentication steps
Auth Method Structure:
{
  "authMethod": [
    {
      "order": 1,
      "allowedMethods": [
        {
          "type": "password"
        },
        {
          "type": "otp"
        }
      ]
    },
    {
      "order": 2,
      "allowedMethods": [
        {
          "type": "google"
        }
      ]
    }
  ]
}
Validation Rules:
  • Must have between 1 and 3 authentication steps
  • Each step must have a unique order number
  • At least one authentication method is required per step
  • No duplicate authentication methods within the same step
  • No duplicate authentication methods across different steps
  • Each authentication method can only be used once in the entire configuration
Supported Authentication Types:
  • password - Username/password authentication
  • otp - One-time password via email
  • google - Google OAuth authentication
  • microsoft - Microsoft OAuth authentication
  • azureAd - Azure Active Directory authentication
  • oauth - Generic OAuth authentication
  • samlSso - SAML Single Sign-On
Initialize organization authentication configuration.
  • Request
  • Response
Endpoint: POST /api/v1/orgAuthConfig/Headers:
HeaderValueRequiredDescription
AuthorizationBearer YesValid admin access token
Request Body Parameters:
ParameterTypeRequiredDescription
contactEmailstringYesOrganization contact email
registeredNamestringYesOrganization registered name
adminFullNamestringYesAdmin’s full name
sendEmailbooleanNoWhether to send email notifications (default: false)
{
  "contactEmail": "admin@example.com",
  "registeredName": "Example Corporation",
  "adminFullName": "John Admin",
  "sendEmail": false
}
Internal service-to-service endpoints for configuration and validation.
Check if password authentication is enabled for the organization.
  • Request
  • Response
Endpoint: GET /api/v1/userAccount/internal/password/checkHeaders:
HeaderValueRequiredDescription
AuthorizationBearer YesValid scoped token with FETCH_CONFIG scope

Security Considerations

The Authentication Service implements several security measures:

Password Security

  • Passwords are validated for complexity requirements (minimum 8 characters with at least one uppercase, one lowercase, one number, and one special character)
  • Passwords are hashed using bcrypt with salt rounds
  • Password reset links have limited validity

Brute Force Protection

  • Failed login attempts are tracked per user account
  • Accounts are automatically blocked after 5 consecutive failed attempts
  • Suspicious login attempts trigger notification emails
  • Blocked accounts require admin intervention to restore access

Session Security

  • Session tokens are generated as UUIDs
  • Sessions have limited lifetime (default: 1 hour) and are stored in Redis
  • Sessions are invalidated after successful authentication or timeout
  • Session data is encrypted and contains minimal user information

JWT Security

  • Tokens are signed with secure secrets
  • Different scopes are used for different token types (auth, refresh, password reset, etc.)
  • Access tokens have short lifetimes (typically 1 hour)
  • Refresh tokens have longer lifetimes (typically 7 days)

OAuth Security

  • OAuth tokens are validated against provider endpoints
  • Email verification ensures token authenticity
  • Provider-specific validation for Google, Microsoft, and Azure AD
  • Generic OAuth support with configurable endpoints

SAML Security

  • SAML responses are cryptographically verified
  • Certificate-based validation
  • Configurable email field mapping
  • Relay state protection against CSRF attacks

Error Handling

All endpoints return structured error responses:
{
  "error": {
    "code": "AUTHENTICATION_FAILED",
    "message": "Invalid credentials provided",
    "details": {
      "field": "password",
      "issue": "Password does not match"
    }
  }
}
Common Error Codes:
  • AUTHENTICATION_FAILED - Invalid credentials
  • SESSION_EXPIRED - Session token expired
  • INVALID_TOKEN - Invalid or malformed token
  • USER_BLOCKED - Account is blocked due to failed attempts
  • VALIDATION_ERROR - Invalid request parameters
  • UNAUTHORIZED - Missing or invalid authentication
  • FORBIDDEN - Insufficient permissions
  • NOT_FOUND - Resource not found
  • INTERNAL_ERROR - Server error

Important Notes

  1. Session Token Management: The x-session-token header is critical for multi-step authentication flows
  2. Password Complexity: Passwords must meet minimum security requirements
  3. Account Blocking: Users are automatically blocked after 5 failed login attempts
  4. Token Scopes: Different endpoints require different token scopes for access
  5. Multi-Factor Authentication: Organizations can configure multiple authentication steps
  6. Provider Configuration: OAuth and SAML providers require proper configuration
  7. Email Validation: All email fields are validated for proper format
  8. Security Headers: Proper headers must be included for authentication flows
I