Overview
Ironclad provides a powerful role-based authorization system using custom Actix-web extractors. This allows you to declaratively enforce access control at the handler level.Role System
Ironclad includes a type-safe role system with four built-in roles:role.rs:4-10.
Role Methods
role.rs:12-40.
Authorization Extractors
Ironclad provides several extractors for different authorization levels. All extractors verify JWT tokens and extract claims automatically.AuthUser - Any Authenticated User
The most basic extractor that allows any authenticated user:authentication.rs:10-20 for the implementation.
AdminUser - Admin Only
Restricts access to users with theadmin role:
authentication.rs:25-43 for the implementation.
Example from the codebase:
auth_controller.rs:31-39.
ModeratorUser - Admin or Moderator
Allows access to both admins and moderators:authentication.rs:48-66 for the implementation.
PremiumUser - Admin, Moderator, or Premium
Allows access to premium features for multiple role types:authentication.rs:71-89 for the implementation.
RoleUser - Flexible Role Checking
Provides flexible role checking methods for custom authorization logic:authentication.rs:94-130 for the implementation.
RoleUser Methods
authentication.rs:97-121.
JWT Claims
All extractors work with JWT claims that contain user information:user.rs:152-159.
Claims Methods
user.rs:161-170.
How Extractors Work
All authorization extractors implement Actix-web’sFromRequest trait. Here’s how they work:
Token Extraction
authentication.rs:135-148.
AdminUser Implementation
authentication.rs:28-43.
Authorization Utilities
Ironclad provides utility functions for common authorization patterns:Verify Self or Admin
Allows users to access their own resources or admins to access any resource:auth.rs:23-29.
Verify Admin
auth.rs:31-37.
Dynamic Role Validation Macro
For runtime role validation, use therequire_any_role! macro:
authentication.rs:153-167.
Route Configuration Examples
Basic Protected Route
Role-Based Route Groups
Mixed Authorization Levels
Error Handling
All extractors return appropriate error responses:Unauthorized (401)
Returned when:- No Authorization header is present
- Token is invalid or expired
- Token signature verification fails
Forbidden (403)
Returned when:- User is authenticated but lacks required role
- User tries to access resources they don’t own
Testing Authorization
Test authorization logic with mock claims:authentication.rs:169-185.
Best Practices
Use the Most Specific Extractor
Choose the extractor that matches your security requirements:Combine with Path Parameters
Useverify_self_or_admin for user-specific resources:
Use RoleUser for Complex Logic
When you need multiple authorization checks:Related Documentation
Authentication
Learn about user registration, login, and JWT tokens
JWT Tokens
Deep dive into JWT token generation and validation