Authentication
Secure your actors with authentication and authorization
Rivet provides multiple authentication methods to secure your actors. Use onAuth
for server-side validation or onBeforeConnect
for actor-level authentication.
Authentication Methods
onAuth Hook (Recommended)
The onAuth
hook runs on the HTTP server before clients can access actors. This is the preferred method for most authentication scenarios.
onBeforeConnect
Hook
Use onBeforeConnect
when you need access to actor state for authentication:
Notice
Prefer onAuth
over onBeforeConnect
when possible, as onAuth
runs on the HTTP server and uses fewer actor resources.
Connection Parameters
Pass authentication data when connecting:
Intent-Based Authentication (Experimental)
The onAuth
hook receives an intents
parameter indicating what the client wants to do:
Error Handling
Authentication Errors
Use specific error types for different authentication failures:
Client Error Handling
Handle authentication errors on the client:
Integration with Auth Providers
Better Auth Integration
JWT Authentication
API Key Authentication
Role-Based Access Control
Implement RBAC with helper functions:
Testing Authentication
Mock authentication for testing:
Best Practices
- Use onAuth: Prefer
onAuth
overonBeforeConnect
for most authentication - Validate Early: Authenticate at the HTTP server level when possible
- Specific Errors: Use appropriate error types (Unauthorized, Forbidden)
- Rate Limiting: Consider rate limiting in your authentication logic
- Token Refresh: Handle token expiration gracefully on the client
- Audit Logging: Log authentication events for security monitoring
- Least Privilege: Only grant the minimum permissions needed