Lewati ke konten utama
menjadi.dev
Backend

Authorization

Proses menentukan apa yang boleh dilakukan user setelah dia terautentikasi.

Authorization adalah proses menentukan hak akses user setelah identitasnya terverifikasi (authentication selesai). Authorization menjawab pertanyaan ‘User ini boleh melakukan apa?’ Contoh: User A boleh mengedit post sendiri tapi tidak post orang lain. User admin boleh mengakses dashboard, user biasa tidak. Pendekatan authorization: RBAC (Role-Based Access Control — hak berdasarkan role: admin, editor, viewer), ABAC (Attribute-Based Access Control — hak berdasarkan atribut: user department, time of day, location), dan ACL (Access Control List — daftar spesifik siapa bisa akses apa). Middleware authorization ditempatkan setelah authentication middleware di route handler.

Contoh Kode

// RBAC Middleware dengan Hono
app.use('/admin/*', async (c, next) => {
  const user = c.get('user');
  if (user.role !== 'admin') {
    return c.json({ error: 'Forbidden' }, 403);
  }
  await next();
});

// Resource-level authorization
app.put('/posts/:id', async (c) => {
  const post = await getPost(c.req.param('id'));
  const user = c.get('user');
  
  // User hanya boleh edit post sendiri
  if (post.authorId !== user.id && user.role !== 'admin') {
    return c.json({ error: 'Unauthorized' }, 403);
  }
  // ...
});

Istilah Terkait