Authentication overview
Segment relies on different authentication mechanisms depending on the interface being accessed and the nature of the interaction. For collecting customer data via its SDKs and client-side libraries, Segment primarily uses API keys, which are unique identifiers distinguishing data sources and ensuring events are routed to the correct workspace. For programmatic access to Segment's administrative features, such as managing workspaces, sources, destinations, or retrieving user data through its Public API, Segment utilizes OAuth 2.0, an industry-standard authorization framework for delegated access. Understanding these distinct methods is crucial for securely integrating with Segment, whether you are tracking user behavior on a website or automating data platform configurations.
The choice of authentication method aligns with the principle of least privilege, ensuring that client-side applications only have the necessary permissions to send data, while server-side or administrative tools can access and modify configurations with appropriate authorization. All data transmission to Segment is secured using HTTPS/TLS encryption, providing confidentiality and integrity for the data in transit. For detailed information on Segment's security practices, refer to their official Segment security overview documentation.
Supported authentication methods
Segment supports several authentication methods tailored to different use cases:
- API Keys (Write Keys / Source API Keys): These are primarily used for sending data from a source (e.g., a website, mobile app, or server-side application) to Segment. Each source in Segment is assigned a unique Write Key. When data is sent, this key identifies the source and ensures the data is correctly attributed and routed within your Segment workspace. These keys are generally included in the request payload or HTTP headers. Segment distinguishes between client-side (public) and server-side (private) API keys for added security.
- Tracking API Keys: Specifically for server-side tracking, these keys are intended to be kept confidential and never exposed in client-side code. They grant broader permissions than client-side keys, allowing for more sensitive operations like identifying users and tracking events from backend systems.
- OAuth 2.0: This protocol is used for authenticating with Segment's Public API (also known as the Admin API). OAuth 2.0 enables applications to obtain limited access to user accounts on an HTTP service, such as Segment, without giving the application the user's password. It's suitable for integrations that manage Segment resources or access administrative data. Applications typically request an access token after user authorization, which is then used in API requests via the
Authorization: Bearer <TOKEN>header. OAuth 2.0 specification details are available from the IETF.
The table below summarizes Segment's authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| API Key (Client-side / Public Write Key) | Collecting data from web browsers, mobile apps, or other publicly accessible client applications. | Moderate (intended for public exposure; only allows data ingestion) |
| API Key (Server-side / Tracking API Key) | Collecting data from backend servers, CRMs, data warehouses, or other secure server applications. | High (requires strict confidentiality; enables server-side tracking and identification) |
| OAuth 2.0 (Public API Access) | Programmatic access to Segment's administrative APIs for managing workspace configurations, accessing user profiles, or automating tasks. | High (requires user consent, token-based access with scopes) |
Getting your credentials
Obtaining the necessary authentication credentials for Segment depends on the method you intend to use:
API Keys (Write Keys / Tracking API Keys)
- Log in to your Segment Workspace: Access your Segment account through the web interface.
- Navigate to Sources: In the Segment dashboard, go to the 'Connections' section and select 'Sources'.
- Select or Create a Source: Choose an existing source or create a new one for your application. Each source type (e.g., JavaScript, Node.js) will have its own configuration.
- Locate the Write Key: Within the source's settings, you will find the 'Write Key' or 'API Key'. For client-side sources, this key is often displayed prominently. For server-side sources, you'll find the Tracking API Key. Segment provides specific instructions for configuring various source types.
Important: Treat your server-side API keys as sensitive credentials. Never expose them in client-side code or public repositories.
OAuth 2.0 Credentials (for Public API Access)
To use OAuth 2.0 with Segment's Public API, you typically need to register your application with Segment to obtain Client ID and Client Secret, and set up redirect URIs. This process is common for OAuth implementations, as described in RFC 6749: The OAuth 2.0 Authorization Framework. Segment's developer documentation provides guidance on accessing the Public API, which includes details on OAuth flow. While the exact steps for registering an application for OAuth may vary, they generally involve:
- Accessing Developer Settings: Within your Segment workspace, look for developer or API settings.
- Registering a New OAuth Application: Provide details such as application name, description, and crucial redirect URIs. These URIs are where Segment will send the user back to your application after they authorize access.
- Obtaining Client ID and Client Secret: Upon successful registration, Segment will issue your application a unique Client ID and Client Secret. The Client Secret must be kept confidential.
- Implementing the OAuth Flow: Your application will initiate an authorization request, redirecting the user to Segment for consent. After consent, Segment redirects the user back to your specified URI with an authorization code, which your application exchanges for an access token and refresh token.
Authenticated request example
The following examples illustrate how to authenticate requests to Segment using both an API Key for data collection and an OAuth 2.0 access token for administrative API calls.
JavaScript Client-side Tracking (with API Key)
When using the Segment JavaScript SDK (Analytics.js), the Write Key is typically initialized when the SDK is loaded on your webpage. This example shows how to initialize the SDK and then track an event:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script>
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","page","identify","reset","group","track","ready","alias","debug","pageview","load","setAnonymousId","addSourceMiddleware","addIntegrationMiddleware","addDestinationMiddleware","setBufferQueue","startBuffer","flushBuffer"];analytics.factory=function(e){return function(){var t=Array.prototype.slice.call(arguments);t.unshift(e);analytics.push(t);return analytics}};for(var e=0;e<analytics.methods.length;e++){var key=analytics.methods[e];analytics[key]=analytics.factory(key)}analytics.load=function(key,e){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.src="https://cdn.segment.com/analytics.js/v1/"+key+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(t,n)};analytics.SNIPPET_VERSION="4.13.1";
analytics.load("YOUR_WRITE_KEY"); // Replace with your actual Write Key
analytics.page();
}}
</script>
</head>
<body>
<h1>Welcome to my site!</h1>
<button onclick="analytics.track('Button Clicked', { buttonName: 'Call to Action' });">Click Me</button>
</body>
</html>
Python Server-side Tracking (with API Key)
For server-side applications, the Tracking API Key is typically passed directly to the Segment SDK initialization. This example uses the Segment Python SDK:
import segment.analytics as analytics
import os
# Configure with your Tracking API Key (e.g., from environment variables)
analytics.write_key = os.environ.get('SEGMENT_TRACKING_API_KEY')
# Identify a user
analytics.identify('user-123', {
'name': 'John Doe',
'email': '[email protected]'
})
# Track an event
analytics.track('user-123', 'Product Viewed', {
'product_id': '56789',
'product_name': 'Segment Widget'
})
# Flush events (important for server-side to ensure delivery)
analytics.flush()
cURL Request to Public API (with OAuth 2.0)
After obtaining an OAuth 2.0 access token, you can use it to make requests to Segment's Public API. This example fetches a list of sources:
curl -X GET \
'https://api.segment.com/v1/sources' \
-H 'Authorization: Bearer YOUR_OAUTH_ACCESS_TOKEN' \
-H 'Content-Type: application/json'
Replace YOUR_OAUTH_ACCESS_TOKEN with a valid OAuth 2.0 access token obtained through the authorization flow. The Segment Public API documentation provides further examples and endpoint details.
Security best practices
Adhering to security best practices is essential when implementing Segment authentication:
- Protect API Keys: Never hardcode server-side API keys directly into your application's source code, especially for public repositories. Instead, store them in environment variables, secret management services (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault), or secure configuration files. For client-side keys, while they are publicly exposed, ensure they only have the minimum necessary permissions (data ingestion) and cannot be used for administrative actions.
- Use HTTPS/TLS Everywhere: Ensure all communication with Segment is over HTTPS. Segment enforces this by default, but it's important to verify that your application's environment is configured to use secure connections. Transport Layer Security (TLS) is critical for protecting data in transit from eavesdropping and tampering, as outlined by the Cloudflare TLS overview.
- Implement OAuth 2.0 Securely: When using OAuth 2.0 for the Public API, follow standard security practices:
- Keep Client Secrets Confidential: Never expose your Client Secret in client-side code.
- Validate Redirect URIs: Ensure your registered redirect URIs are specific and secure to prevent authorization code interception.
- Use PKCE (Proof Key for Code Exchange): For public clients (e.g., mobile apps, SPAs), PKCE adds an extra layer of security to the authorization code flow, mitigating interception attacks.
- Minimize Scope: Request only the minimum necessary permissions (scopes) when obtaining an access token.
- Secure Token Storage: Store access and refresh tokens securely, typically in HTTP-only cookies or encrypted storage where appropriate.
- Regular Key Rotation: Periodically rotate your API keys and OAuth client secrets. This practice limits the window of exposure if a key is compromised.
- Monitor API Usage: Regularly monitor your Segment usage and API logs for any unusual activity that could indicate unauthorized access or misuse of credentials. Segment provides tools and logs within the workspace to facilitate this.
- Principle of Least Privilege: Grant only the necessary permissions to users and applications. For instance, a client-side API key should only be able to send data, not modify workspace settings.
- Review Segment's Security Documentation: Stay updated with Segment's official security recommendations and documentation, as practices may evolve. Their security overview and Public API authentication guide are valuable resources.