Authentication overview
Pusher provides real-time communication services, primarily through Pusher Channels for publish/subscribe messaging and Pusher Beams for push notifications. Authentication for these services is designed to manage access control, ensuring that only authorized clients can subscribe to specific channels or receive notifications. The core principle involves differentiating between public channels, which require no explicit authentication, and private or presence channels, which demand server-side verification of a user's identity and their permission to access a channel (Pusher authentication flow documentation).
For server-to-Pusher interactions, such as publishing messages or triggering events, a set of application credentials—an App ID, Key, and Secret—are used to sign requests. This ensures that only your backend server can interact with your Pusher application in a privileged manner. For client-side interactions with private or presence channels, Pusher employs a token-based authentication mechanism. The client makes a request to a dedicated authentication endpoint on your application's server. Your server then verifies the user's identity and permissions, and if authorized, generates an authentication signature which is returned to the client. This signature allows the client to subscribe to the restricted channel securely, without ever exposing sensitive API secrets directly in client-side code (Pusher client authorization).
This approach aligns with common security practices for web applications, where sensitive operations and credentials are kept server-side. The use of signed tokens for client authorization is a widely adopted pattern, often seen in OAuth 2.0 and OpenID Connect flows, which rely on cryptographic signatures to verify the integrity and authenticity of access tokens (OAuth 2.0 grant types).
Supported authentication methods
Pusher primarily supports two authentication contexts:
- Server-side authentication: Used by your backend application to interact with the Pusher HTTP API, for actions like publishing messages to channels or sending push notifications.
- Client-side channel authorization: Used by client applications (e.g., web browsers, mobile apps) to subscribe to private or presence channels. This involves a server-side authentication endpoint that verifies client permissions.
Authentication method details
The following table outlines the primary authentication methods and their appropriate use cases within the Pusher ecosystem:
| Method | When to Use | Security Level |
|---|---|---|
| API Key & Secret (Server-side) | Publishing messages to any channel (public, private, presence), sending push notifications, querying channel state. Used by your backend server or trusted environments. | High. Credentials are kept secret on the server and used to sign requests, preventing unauthorized API access. |
| Authentication Endpoint (Client-side Channel Authorization) | Subscribing client applications to private- or presence- prefixed channels. The client requests a signature from your server, which then interacts with Pusher. |
High. The sensitive API Secret remains on your server. Your server validates the client's identity and permissions before generating a unique authorization signature. |
| Public Channels (No Auth) | Subscribing client applications to public- prefixed channels (e.g., my-channel). No explicit authentication is required for subscription. |
Low (for subscription). Data published to public channels is accessible to any client that knows the channel name and your App Key. Security relies on not transmitting sensitive data over public channels. |
The authentication endpoint method for client-side channel authorization is critical for building secure real-time applications. It ensures that your backend maintains full control over who can access specific data streams, preventing unauthorized users from eavesdropping on private conversations or manipulating shared states (Pusher server authorization).
Getting your credentials
To use Pusher, you first need to create an application within the Pusher Dashboard. Upon creation, Pusher will provide you with the necessary credentials:
- App ID: A unique identifier for your Pusher application.
- App Key: A public key used by client applications to connect to Pusher. While it's public, it's not sensitive on its own.
- App Secret: A highly sensitive private key used by your server-side application to authenticate with the Pusher HTTP API. This must never be exposed in client-side code.
- Cluster: The geographical region where your Pusher application servers reside (e.g.,
mt1for US East).
Steps to obtain credentials:
- Create a Pusher Account: If you don't have one, sign up on the Pusher homepage.
- Create a New App: Navigate to the Pusher Dashboard and click 'Create new app'.
- Configure App Details: Provide an app name, select a cluster, and choose a frontend and backend technology stack. These choices primarily influence the example code provided.
- Retrieve Credentials: After creating the app, go to the 'App Keys' section of your application settings. Here you will find your App ID, App Key, App Secret, and Cluster information.
It is crucial to treat your App Secret with the same care as any other sensitive API key. Store it securely, preferably using environment variables or a secrets management service, and ensure it is never committed to version control systems directly or exposed in client-side code (Google API key best practices).
Authenticated request example
This section demonstrates how to publish a message to a private channel using a Node.js backend. This involves authenticating with your App ID, Key, and Secret.
Server-side publishing example (Node.js)
First, ensure you have the Pusher Node.js library installed:
npm install pusher
Then, set up your Pusher instance with your credentials, typically loaded from environment variables:
// server.js
const Pusher = require('pusher');
require('dotenv').config(); // For loading environment variables
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
useTLS: true,
});
// Example: Publishing a message to a private channel
pusher.trigger('private-my-chat-channel', 'new-message', {
message: 'Hello from the server!',
sender: 'System'
});
console.log('Message published to private-my-chat-channel');
// Example: Implementing a client-side authentication endpoint
// This endpoint would be called by your frontend when a client tries to subscribe
// to a private or presence channel.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/pusher/auth', (req, res) => {
const socketId = req.body.socket_id;
const channelName = req.body.channel_name;
// In a real application, you would verify the user's identity and permissions here.
// For demonstration, we'll assume the user is authorized for 'private-my-chat-channel'.
// You might check session data, JWTs, or database records.
const userId = req.session.userId; // Example: get user ID from session
const isAuthorized = true; // Placeholder for actual authorization logic
if (isAuthorized) {
const auth = pusher.authenticate(socketId, channelName);
res.send(auth);
} else {
res.status(403).send('Forbidden');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Auth server running on port ${PORT}`);
});
In this example, process.env.PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET, and PUSHER_APP_CLUSTER should be replaced with your actual values, ideally loaded from a .env file or environment variables for production environments. The /pusher/auth endpoint demonstrates how your server would respond to a client's request to authorize subscription to a private channel, generating the necessary authorization signature (Pusher server authorization guide).
Client-side subscription example (JavaScript)
On the client-side, your JavaScript application would connect to Pusher and then attempt to subscribe to the private channel, triggering the call to your server's authentication endpoint:
// client.js (browser-side)
const pusher = new Pusher('YOUR_APP_KEY', {
cluster: 'YOUR_APP_CLUSTER',
// This authEndpoint tells Pusher where to send authorization requests
authEndpoint: '/pusher/auth', // Your server-side auth endpoint
auth: {
headers: { // Include any necessary headers for your server to identify the user
'X-CSRF-Token': 'your_csrf_token_here' // Example: CSRF token for session-based auth
}
}
});
const channel = pusher.subscribe('private-my-chat-channel');
channel.bind('new-message', function(data) {
alert('Received message: ' + data.message + ' from ' + data.sender);
});
channel.bind('pusher:subscription_succeeded', function() {
console.log('Successfully subscribed to private-my-chat-channel');
});
channel.bind('pusher:subscription_error', function(status) {
console.error('Subscription error:', status);
});
Replace 'YOUR_APP_KEY' and 'YOUR_APP_CLUSTER' with your actual Pusher App Key and Cluster. The authEndpoint configuration is crucial, pointing to the server-side endpoint responsible for generating the authorization signature (Pusher client authorization guide).
Security best practices
Securing your Pusher implementation is paramount to protect your users' data and prevent unauthorized access to your real-time features. Adhere to these best practices:
- Never expose your App Secret: The Pusher App Secret must remain strictly server-side. Never embed it in client-side code, commit it to public repositories, or include it in client-facing bundles. Exposure of the App Secret grants full control over your Pusher application.
- Use environment variables for credentials: Store your App ID, Key, Secret, and Cluster in environment variables (e.g.,
.envfiles for development, or cloud provider secrets managers for production) instead of hardcoding them directly in your application code. This prevents accidental exposure and simplifies credential rotation (Azure Key Vault best practices). - Implement robust server-side authorization: Your authentication endpoint for private and presence channels must perform thorough validation. Verify the requesting user's identity and their permissions for the specific channel they are attempting to subscribe to. Do not simply return an authorization signature without proper checks. Utilize your existing authentication system (e.g., session management, JWT verification) to confirm the user's legitimacy.
- Use private and presence channels for sensitive data: For any data that should not be publicly accessible, use
private-orpresence-prefixed channels. These channels enforce your server-side authorization logic, ensuring only authorized users can subscribe. - Enable TLS/SSL: Ensure all connections to Pusher are encrypted using TLS/SSL (
useTLS: truein Pusher SDKs). This protects data in transit from eavesdropping and tampering. Pusher enforces TLS for all connections by default. - Regularly rotate API secrets: Periodically change your App Secret, especially if there's any suspicion of compromise. Pusher allows you to regenerate your App Secret from the dashboard.
- Monitor for suspicious activity: Keep an eye on your Pusher dashboard analytics for unusual spikes in connections, messages, or unauthorized access attempts. Implement logging on your authentication endpoint to track successful and failed authorization requests.
- Sanitize and validate all input: Whether publishing messages or handling channel names, always sanitize and validate all data originating from clients to prevent injection attacks or malformed requests.