Authorization

Route protection and role-based access control with Kavach.

Route Rules

Define protection rules in your configuration:

rules: [
  { path: '/', public: true },
  { path: '/about', public: true },
  { path: '/dashboard', protected: true },
  { path: '/admin', roles: ['admin'] },
  { path: '/moderator', roles: ['moderator', 'admin'] },
  { path: '/api/data', roles: ['user', 'admin'] }
]

Rule Types

public: true

Accessible without authentication.

protected: true

Requires authentication (any logged-in user).

roles: ['role1', 'role2']

Restricts access to specific roles.

Role-Based Redirects

After login, redirect users to role-specific pages:

roleHome: {
  admin: '/admin',
  moderator: '/dashboard',
  user: '/dashboard'
}

Using Sentry

For fine-grained control, use Sentry directly:

import { createSentry } from '@kavach/sentry'

const sentry = createSentry({
  rules: [
    { path: '/admin', roles: ['admin'] },
    { path: '/dashboard', protected: true }
  ],
  roleHome: {
    admin: '/admin',
    user: '/dashboard'
  }
})

Behavior

ScenarioBehavior
Unauthenticated → protected302 redirect to login
Wrong role302 redirect to role home
API endpoint unauthorized401/403 status code
Page unauthorized302 redirect

Next Steps

Kavach — Authentication made simple llms.txt