Authentication
Secure your actors with authentication and authorization.
Do You Need Authentication?
Actors are private by default on Rivet Cloud. Only requests with the publishable token can interact with actors.
- Backend-only actors: If your publishable token is only included in your backend, then authentication is not necessary.
- Frontend-accessible actors: If your publishable token is included in your frontend, then implementing authentication is recommended.
Authentication Connections
Authentication is configured through either:
onBeforeConnectfor simple pass/fail validationcreateConnStatewhen you need to access user data in your actions viac.conn.state
onBeforeConnect
The onBeforeConnect hook validates credentials before allowing a connection. Throw an error to reject the connection.
createConnState
Use createConnState to extract user data from credentials and store it in connection state. This data is accessible in actions via c.conn.state. Like onBeforeConnect, throwing an error will reject the connection. See connections for more details.
Available Auth Data
Authentication hooks have access to several properties:
| Property | Description |
|---|---|
params | Custom data passed by the client when connecting (see connection params) |
c.request | The underlying HTTP request object |
c.request.headers | Request headers for tokens, API keys (does not work for .connect()) |
c.state | Actor state for authorization decisions (see state) |
c.key | The actor's key (see keys) |
It's recommended to use params instead of c.request.headers whenever possible since it works for both HTTP & WebSocket connections.
Client Usage
Passing Credentials
Pass authentication data when connecting:
Handling Errors
Authentication errors use the same system as regular errors. See errors for more details.
Examples
JWT
Validate JSON Web Tokens and extract user claims:
External Auth Provider
Validate credentials against an external authentication service:
Using c.state In Authorization
Access actor state via c.state and the actor's key via c.key to make authorization decisions:
Role-Based Access Control
Create helper functions for common authorization patterns:
Rate Limiting
Use c.vars to track connection attempts and rate limit by user:
The limits in this example are ephemeral. If you wish to persist rate limits, you can optionally replace vars with state.
Caching Tokens
Cache validated tokens in c.vars to avoid redundant validation on repeated connections. See ephemeral variables for more details.
API Reference
AuthIntent- Authentication intent typeOnBeforeConnectContext- Context for auth checksOnConnectContext- Context after connection