React JS sebagai Frontend SSO - Perwira Learning Center

 


Halo teman teman, kembali lagi di artikel saya, kali ini saya akan menjelaskan materi kebalikan dari artikel sebelumnya yaitu React JS sebagai frontend SSO

Arsitektur React sebagai Frontend SSO

1. State Management untuk Auth

Zustand Store menyimpan:

  • User info (id, email, name, roles)
  • Authentication status (sudah login atau belum)
  • Token (access & refresh)

Kenapa Zustand?

  • Lebih ringan dari Redux
  • Sederhana untuk state global
  • Perfect untuk auth state yang perlu diakses banyak component

2. Axios Interceptors - Otomasi Token Management

Request Interceptor:

  • Sebelum setiap API call, otomatis attach access token ke header
  • Frontend tidak perlu manual set header di setiap API call
  • Format: Authorization: Bearer <access_token>

Response Interceptor:

  • Deteksi error 401 (Unauthorized)
  • Otomatis coba refresh token
  • Jika refresh berhasil → retry request yang gagal tadi
  • Jika refresh gagal → redirect ke login

Benefit:

  • User experience mulus, tidak terasa token refresh
  • Developer tidak perlu handle token refresh manual di setiap component

3. Protected Routes

Konsep:

  • Beberapa halaman hanya bisa diakses kalau sudah login
  • Beberapa halaman butuh role tertentu

Cara kerja:

  • React Router wrapped dengan ProtectedRoute component
  • ProtectedRoute cek authentication status
  • Jika belum login → redirect ke /login
  • Jika login tapi role tidak cocok → redirect ke /unauthorized
  • Jika semua OK → render halaman yang diminta
  • 4. Token Storage Strategy

    LocalStorage:

    • Mudah diakses JavaScript
    • Persist setelah browser close
    • Risiko: Rentan XSS attack (malicious script bisa curi token)

    SessionStorage:

    • Hilang setelah tab ditutup
    • Lebih aman dari localStorage
    • Downside: User harus login setiap buka tab baru

    HttpOnly Cookie (Recommended untuk production):

    • Tidak bisa diakses JavaScript
    • Server yang set dan baca
    • Paling aman dari XSS
    • Downside: Butuh konfigurasi CORS yang benar

    Best Practice untuk SCPA:

    • Access token di memory (state)
    • Refresh token di HttpOnly cookie atau secure localStorage
    • Encrypt sensitive data sebelum simpan
    Sekian artikel dari saya , terimakasih dan sampai jumpa di artikel berikutnya!!