Frontend
Authentication
Authentication and Security

Authentication and Security

Overview

The application uses JWT (JSON Web Token) based authentication. Tokens are stored in localStorage and automatically included in all API requests.

Authentication Flow

Login Process

  1. User enters email and password on /login page
  2. Credentials are sent to /api/v1/auth/login endpoint
  3. Backend validates credentials and returns JWT token and user data
  4. Token and user data are stored in localStorage
  5. User is redirected to dashboard

Token Storage

// Token storage
localStorage.setItem("authToken", response.token);
localStorage.setItem("user", JSON.stringify(response.user));

Token Usage

All API requests automatically include the token in the Authorization header:

headers: {
  "Authorization": `Bearer ${authToken}`,
  "Content-Type": "application/json"
}

Automatic Logout

The application automatically logs out users when:

  1. 401 Unauthorized Response: Any API request returns 401 status
  2. Token Expiration: Backend rejects expired tokens
  3. Manual Logout: User clicks logout button

Logout Implementation

function forceLogout() {
  localStorage.removeItem("authToken");
  localStorage.removeItem("user");
  window.location.href = "/login";
}

The forceLogout() function is called automatically by the API client when a 401 response is detected.

Protected Routes

All dashboard routes (/dashboard/*) require authentication. The application checks for token presence, but route protection is primarily handled by:

  1. API Response Handling: 401 responses trigger logout
  2. Manual Checks: Components can check for token before rendering

User Data

User data is stored in localStorage after login:

interface User {
  id: number;
  telegram_id: number;
  username: string;
  first_name: string;
  last_name: string;
  email: string;
  roles: string[];
  ecosystems: string[];
  topics: string[];
  // ... other fields
}

Security Best Practices

1. Token Security

  • Never expose tokens in URLs or logs
  • Use HTTPS in production
  • Implement token refresh (if supported by backend)
  • Clear tokens on logout

2. Input Validation

  • Validate all user inputs before sending to API
  • Sanitize data before rendering
  • Use TypeScript for type safety

3. Error Handling

  • Don't expose sensitive errors to users
  • Log errors for debugging (without sensitive data)
  • Handle network errors gracefully

4. API Security

  • Validate API responses before using data
  • Handle malformed responses safely
  • Implement request timeouts
  • Use proper error messages (don't leak system info)

Login Component

The login page (src/pages/LoginPage.tsx) handles authentication:

const handleLogin = async (e: React.FormEvent) => {
  e.preventDefault();
  setLoading(true);
 
  try {
    const response = await apiClient.login(email, password);
    localStorage.setItem("authToken", response.token);
    localStorage.setItem("user", JSON.stringify(response.user));
    toast.success("Login successful!");
    navigate("/dashboard/users");
  } catch (error) {
    toast.error("Invalid credentials. Please check your email and password.");
  } finally {
    setLoading(false);
  }
};

Logout Implementation

Logout is handled in the sidebar component:

const handleLogout = () => {
  localStorage.removeItem("authToken");
  localStorage.removeItem("user");
  toast.success("Logged out successfully");
  navigate("/login");
};

API Client Authentication

The API client (src/lib/api.ts) handles authentication automatically:

private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const authToken = localStorage.getItem("authToken");
  
  const config: RequestInit = {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(authToken && { Authorization: `Bearer ${authToken}` }),
      ...options.headers,
    },
  };
  
  // ... request handling with 401 detection
}

Session Management

Currently, the application uses localStorage for session management. For enhanced security, consider:

  1. Token Refresh: Implement automatic token refresh before expiration
  2. Session Timeout: Add automatic logout after inactivity
  3. Secure Storage: Consider using httpOnly cookies (requires backend support)
  4. Multi-factor Authentication: Add 2FA support if needed

Common Security Issues to Avoid

  1. XSS (Cross-Site Scripting): Always sanitize user inputs
  2. CSRF (Cross-Site Request Forgery): Use CSRF tokens if needed
  3. Token Theft: Never log or expose tokens
  4. Insecure Storage: Consider more secure storage options for sensitive data
  5. Missing Validation: Always validate inputs on both client and server

Environment-Specific Configuration

Development

  • Base URL: http://localhost:8080
  • Less strict security (for development convenience)

Production

  • Base URL: https://ibw-app-service.lemonpebble-d3abe181.southeastasia.azurecontainerapps.io
  • HTTPS required
  • Strict security headers
  • Token validation enforced