Skip to main content

Overview

The rbac middleware provides role-based access control, allowing you to restrict routes based on user roles and permissions. Use it when you need:
  • Role-based route protection
  • Permission-based access control
  • Multi-level authorization

Installation

Quick Start

Configuration

Options

Examples

Simple Role Check

Permission-Based

Hierarchical Roles

Custom Error Handler

Route Groups

API Reference

Functions

Hierarchy

Technical Details

Implementation Overview

The RBAC middleware is built around a User struct that contains roles and permissions:

Context Management

User information is stored in the request context using a private context key:
  • Set(c *mizu.Ctx, user *User) - Stores user in context
  • Get(c *mizu.Ctx) *User - Retrieves user from context
  • Returns nil if no user is found in context

Role and Permission Checking

The middleware provides several helper functions for checking access:
  • HasRole(c *mizu.Ctx, role string) bool - Checks if user has a specific role
  • HasAnyRole(c *mizu.Ctx, roles ...string) bool - Checks if user has any of the specified roles
  • HasAllRoles(c *mizu.Ctx, roles ...string) bool - Checks if user has all specified roles
  • HasPermission(c *mizu.Ctx, permission string) bool - Checks if user has a specific permission

Middleware Functions

Role-based middlewares:
  • RequireRole(role string) - Requires a specific role
  • RequireAnyRole(roles ...string) - Requires any of the specified roles (OR logic)
  • RequireAllRoles(roles ...string) - Requires all specified roles (AND logic)
Permission-based middlewares:
  • RequirePermission(permission string) - Requires a specific permission
  • RequireAnyPermission(permissions ...string) - Requires any of the permissions
  • RequireAllPermissions(permissions ...string) - Requires all permissions
Convenience middlewares:
  • Admin() - Shorthand for RequireRole(“admin”)
  • Authenticated() - Checks if any user is present in context

Error Handling

  • Default behavior returns HTTP 403 Forbidden with “Access denied” text
  • Returns HTTP 401 Unauthorized with “Authentication required” for unauthenticated users
  • Custom error handlers can be wrapped using WithErrorHandler

Best Practices

  • Use JWT claims or session for role storage
  • Implement role hierarchy for complex permissions
  • Cache permission checks for performance
  • Log authorization failures for security monitoring

Testing