Role-Based Authorization
This guide explains how to implement role-based access control (RBAC) in your SvelteKit application using Svelte Guardian.
Understanding Roles in Svelte Guardian
Role-based authorization allows you to control what users can access based on their assigned roles. Common examples include:
- Admin: Full access to all features
- Editor: Can create and edit content
- Moderator: Can review and approve content
- User: Standard access to protected features
- Guest: Limited access to public features
Setting Up User Roles
1. Database Schema
Svelte Guardian includes a role
field in the default User model. When using Prisma, your schema might look like:
For more complex permission systems, you might create separate models:
2. Including Role in Session
Roles are included in the session by defailt. Simply ensure you use yge role field, or spefify your rolefiel name in roleKey config
Protecting Routes Based on Roles
1. Server-Side Route Protection
Configure route protection in your Svelte Guardian setup:
2. Page-Level Role Checks
In your SvelteKit pages, you can check roles in +page.server.ts
files:
Role-Based UI Elements
1. Conditional UI in Svelte Components
Make UI elements appear based on the user’s role:
2. Creating Reusable Role Guards
Create reusable components to handle role-based UI protection:
//TODO Add this component to library
Using the guard component:
Content Management
This section requires editor privileges.
Request AccessAdvanced Role-Based Features
1. Custom Authorization Logic
For complex permission rules, you can use custom authorization functions(Not yet implemented):
2. Permission-Based Authorization
For more granular control, implement a permission system: //TODO
Use in components:
Best Practices
- Defense in Depth: Never rely only on UI hiding - always enforce role checks on the server
- Principle of Least Privilege: Assign users the minimum roles they need
- Role Auditing: Log role changes for security tracking
- Regular Role Review: Periodically review and update role assignments
- Clear Role Definitions: Clearly document what each role can and cannot do
- Role Inheritance: Design roles to inherit permissions from less privileged roles
- Separation of Concerns: Separate role checking logic from business logic