Authentication overview

Pusher Beams utilizes an authentication model designed to secure both the administration of push notifications and the association of devices with specific users. This involves distinct mechanisms for server-side API interactions and client-side device registration and user identification. The primary method for server-side operations, such as publishing notifications, relies on an Instance ID and a Secret Key, which act as API credentials. For client-side operations that require user-specific context, Pusher Beams supports an optional user authentication flow, typically implemented by generating signed authentication tokens on a trusted server and providing them to client applications Pusher Beams authentication reference.

This separation ensures that sensitive credentials for publishing notifications are never exposed in client-side code, mitigating potential security risks. The system also accommodates various platform-specific requirements for push notification services, such as Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM), by handling the underlying communication with these services on behalf of the developer Pusher Beams documentation.

Supported authentication methods

Pusher Beams supports two primary authentication methods, each serving a different purpose within the notification ecosystem:

  • Instance ID and Secret Key: This method is used for authenticating server-side requests to the Pusher Beams Publish API. The Instance ID identifies your specific Pusher Beams instance, while the Secret Key acts as the cryptographic credential that authorizes API calls. This pair is essential for tasks like sending push notifications to devices or users.
  • User Authentication Tokens: For client-side applications that need to associate a device with a specific user, Pusher Beams employs a user authentication mechanism. This involves your application's backend generating a signed token for a given user ID, which the client-side SDK then uses to authenticate with Pusher Beams. This ensures that only authenticated users can subscribe to user-specific interests and receive personalized notifications. The token generation process typically uses a JSON Web Token (JWT) or a similar signed token format, often leveraging an HMAC-SHA256 algorithm for signing Pusher Beams user authentication.

The following table outlines these methods, their typical use cases, and their security implications:

Method When to Use Security Level
Instance ID & Secret Key Server-side API calls (e.g., publishing notifications, managing instances) High (Secret Key must be kept confidential on server)
User Authentication Tokens Client-side user identification (e.g., associating device with user, subscribing to user-specific interests) Moderate to High (tokens are short-lived, signed by server, client-side exposure is limited)

Getting your credentials

To begin using Pusher Beams, you will need to obtain your Instance ID and Secret Key. These credentials are provided upon creation of a Pusher Beams instance and are accessible through the Pusher Dashboard. The process generally involves:

  1. Account Creation: If you don't already have one, create a Pusher account.
  2. Instance Creation: Navigate to the Beams section of the Pusher Dashboard and create a new Beams instance.
  3. Credential Retrieval: Once an instance is created, your Instance ID and Secret Key will be displayed in the "API Keys" or "Credentials" section for that instance Pusher Beams API Keys.

For user authentication, while the Instance ID is still used on the client-side to identify the Beams instance, the Secret Key is exclusively used on your server to sign the user authentication tokens. Your server code will utilize a server-side SDK (e.g., Node.js, Python, Ruby) to generate these tokens. This ensures the Secret Key remains protected within your server environment Pusher Beams user authentication guide.

Authenticated request example

An authenticated server-side request to publish a notification using Pusher Beams typically involves using your Instance ID and Secret Key with one of the Pusher Beams server SDKs. Here's a conceptual example using a Node.js SDK, demonstrating how to initialize the Beams client and publish a notification:

const PusherPushNotifications = require('@pusher/push-notifications');

let beamsClient = new PusherPushNotifications({
  instanceId: 'YOUR_INSTANCE_ID',
  secretKey: 'YOUR_SECRET_KEY'
});

beamsClient.publishToInterests(
  ['hello'],
  {
    web: {
      notification: {
        title: 'Hello from Pusher!',
        body: 'Your first push notification!',
      }
    },
    apns: {
      aps: {
        alert: {
          title: 'Hello from Pusher!',
          body: 'Your first push notification!',
        }
      }
    },
    fcm: {
      notification: {
        title: 'Hello from Pusher!',
        body: 'Your first push notification!',
      }
    }
  }
).then(() => {
  console.log('Publish successful!');
}).catch((error) => {
  console.error('Error publishing:', error);
});

In this example, YOUR_INSTANCE_ID and YOUR_SECRET_KEY must be replaced with your actual credentials. The publishToInterests method sends the notification to all devices subscribed to the 'hello' interest. The payload includes platform-specific notification details for web, APNs (Apple Push Notification service), and FCM (Firebase Cloud Messaging) Pusher Beams publish to interests reference.

For client-side user authentication, the flow involves your backend generating an authentication token. Here's a conceptual Node.js example for generating such a token:

const PusherPushNotifications = require('@pusher/push-notifications');
const express = require('express');
const app = express();

const beamsClient = new PusherPushNotifications({
  instanceId: 'YOUR_INSTANCE_ID',
  secretKey: 'YOUR_SECRET_KEY',
});

app.get('/pusher/beams-auth', (req, res) => {
  const userId = req.query.user_id; // Get user ID from request (e.g., from session or query param)
  if (!userId) {
    return res.status(400).send('User ID is required');
  }

  try {
    const authData = beamsClient.generateUserToken(userId);
    res.send(authData);
  } catch (error) {
    console.error('Error generating user token:', error);
    res.status(500).send('Internal server error');
  }
});

app.listen(3000, () => {
  console.log('Auth server listening on port 3000');
});

The client application would then make a request to this /pusher/beams-auth endpoint to retrieve the token and provide it to the client-side Beams SDK for user association Pusher Beams user authentication documentation. This pattern aligns with common API security practices where sensitive operations are handled on the server.

Security best practices

Adhering to security best practices is crucial when implementing authentication with Pusher Beams to protect your applications and user data. These practices help prevent unauthorized access, data breaches, and misuse of your notification services.

  • Keep Secret Keys Confidential: Your Pusher Beams Secret Key grants full access to your instance's Publish API. Never expose it in client-side code (web, iOS, Android applications). It should only be used on trusted server-side environments. If a Secret Key is compromised, rotate it immediately through the Pusher Dashboard.
  • Secure User Authentication Endpoints: When implementing user authentication, the endpoint on your server that generates and signs user tokens must be secured. This means:

    • Authenticate Your Users: Ensure that only legitimately authenticated users of your application can request a Pusher Beams user token for their specific user ID. Do not allow unauthenticated access to this endpoint.
    • Use HTTPS: All communication to and from your user authentication endpoint should use HTTPS to encrypt data in transit and protect against eavesdropping Mozilla HTTPS definition.
    • Validate User IDs: Before generating a token, verify that the user_id requested by the client corresponds to the currently authenticated user on your server. This prevents users from impersonating others.
  • Implement Token Expiry: While Pusher Beams user tokens are typically short-lived, ensure that your token generation logic includes a reasonable expiry time. This limits the window of opportunity for a compromised token to be exploited.
  • Regular Key Rotation: Periodically rotate your Pusher Beams Secret Key. This practice minimizes the impact of a potential key compromise over time.
  • Least Privilege Principle: If Pusher Beams introduces more granular access controls in the future, apply the principle of least privilege, granting only the necessary permissions for specific tasks.
  • Monitor for Anomalous Activity: Regularly review your Pusher Beams usage and server logs for any unusual activity that might indicate unauthorized access or misuse of your credentials.
  • Secure Development Lifecycle: Integrate security considerations throughout your entire development lifecycle, from design to deployment and maintenance. This includes regular security audits and vulnerability assessments.