Authentication overview
CPFHub provides an API for secure access to CPF-related services, including CPF Contribution and Statement Retrieval APIs. Authentication is a critical component for every request to ensure that only authorized applications and users can interact with sensitive public sector data. CPFHub's authentication mechanisms are designed to align with Singapore's Personal Data Protection Act (PDPA) and ISO 27001 standards, providing a secure framework for integrations by payroll systems, HR management platforms, and financial planning tools.
The choice of authentication method depends on the integration scenario: direct server-to-server communication typically uses API Keys, while applications requiring user consent for data access implement OAuth 2.0. All authentication processes are managed through the CPFHub Developer Portal, where credentials can be generated and revoked. For details on API endpoints and specific request parameters, refer to the official CPFHub API reference.
Supported authentication methods
CPFHub supports two primary authentication methods to accommodate various integration architectures and security requirements:
- API Key authentication: A credential suitable for server-to-server communication where a trusted backend system makes requests on its own behalf. API keys are long-lived and grant access to specific API scopes as configured in the developer portal.
- OAuth 2.0 (Authorization Code Grant Flow): An open standard for access delegation, commonly used when a user grants a third-party application limited access to their resources without exposing their credentials. This method is ideal for applications that interact with CPFHub on behalf of individual users or organizations, requiring explicit consent. For more information on the OAuth 2.0 standard, consult the OAuth 2.0 documentation.
Authentication methods comparison
| Method | When to Use | Security Level |
|---|---|---|
| API Key | Server-to-server integrations, backend services, trusted applications | High (if managed securely) |
| OAuth 2.0 (Authorization Code Grant) | Third-party applications requiring user consent, applications accessing data on behalf of a user | High (delegated access, short-lived tokens) |
Getting your credentials
Accessing the CPFHub API requires valid credentials, which are provisioned and managed through the CPFHub Developer Portal. The process differs slightly based on the chosen authentication method:
For API Keys
- Sign up/Log in: Navigate to the CPFHub Developer Portal and create an account or log in with existing credentials.
- Create an application: Within your dashboard, create a new application entry. This typically involves providing a name and a brief description.
- Generate API Key: Once your application is created, you will find an option to generate an API key. This key is a unique string that identifies your application.
- Configure scopes: Assign appropriate API scopes to your API key based on the functionalities your application requires (e.g.,
cpf_contribution:read,cpf_statement:write). - Securely store: Immediately store your API key in a secure location. It is visible only once upon generation.
For OAuth 2.0
- Register your application: In the CPFHub Developer Portal, register your application, providing details such as application name, description, and crucially, your redirect URI(s). The redirect URI is where the user will be sent after authorizing your application.
- Obtain Client ID and Client Secret: Upon registration, CPFHub will issue a Client ID and Client Secret for your application. The Client ID is public, but the Client Secret must be kept confidential.
- Configure scopes: Define the necessary API scopes your application will request from users (e.g.,
user:profile:read,employer:data:write). - Implement Authorization Code Flow: Your application will need to initiate the OAuth 2.0 Authorization Code Grant Flow, which involves redirecting the user to CPFHub for authorization, receiving an authorization code, and then exchanging that code for an access token and refresh token using your Client ID and Client Secret. Detailed steps for implementing this flow are available in the CPFHub documentation.
Authenticated request example
This example demonstrates how to make an authenticated request to the CPFHub API using an API Key. The request retrieves a list of CPF contributions. For OAuth 2.0 examples, refer to the CPFHub developer documentation.
Using an API Key (Python example)
Assuming you have obtained an API Key from the CPFHub Developer Portal, you would include it in the Authorization header as a Bearer token.
import requests
import os
# Securely retrieve your API Key (e.g., from environment variables)
CPF_API_KEY = os.environ.get("CPF_HUB_API_KEY")
if not CPF_API_KEY:
raise ValueError("CPF_HUB_API_KEY environment variable not set.")
BASE_URL = "https://api.cpfhub.sg/v1"
ENDPOINT = "/contributions"
headers = {
"Authorization": f"Bearer {CPF_API_KEY}",
"Content-Type": "application/json"
}
# Example: Fetching CPF contributions for a specific period
params = {
"year": 2025,
"month": 4
}
try:
response = requests.get(f"{BASE_URL}{ENDPOINT}", headers=headers, params=params)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
print("Successfully retrieved CPF contributions:")
print(data)
except requests.exceptions.HTTPError as errh:
print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"Something went wrong: {err}")
Security best practices
Adhering to security best practices is essential when integrating with CPFHub to protect sensitive data and maintain compliance with regulations such as PDPA. CPFHub itself is compliant with ISO 27001, an international standard for information security management.
For all authentication methods
- Keep credentials confidential: Never hardcode API Keys or Client Secrets directly into application code. Use environment variables, secure configuration files, or secret management services (e.g., AWS Secrets Manager, Google Secret Manager) to store them.
- Use HTTPS exclusively: All communication with CPFHub APIs must occur over HTTPS to encrypt data in transit and prevent eavesdropping. CPFHub enforces HTTPS for all API endpoints.
- Implement robust error handling: Design your application to gracefully handle authentication failures, network errors, and API rate limits. Avoid exposing sensitive information in error messages.
- Monitor API usage: Regularly review API logs and usage patterns to detect suspicious activity or unauthorized access attempts.
- Stay updated: Keep your SDKs and libraries (e.g., Python requests, Node.js axios) up-to-date to benefit from the latest security patches and improvements.
Specific to API Keys
- Restrict IP addresses: If your infrastructure allows, configure your API key to only accept requests from a specific set of trusted IP addresses.
- Least privilege principle: Assign only the necessary API scopes to your API keys. Avoid granting broad permissions when narrower ones suffice.
- Rotate API Keys: Periodically rotate your API keys (e.g., every 90-180 days) as a preventative measure to mitigate the risk of a compromised key.
- Avoid client-side usage: Never expose API keys directly in client-side code (e.g., JavaScript in a browser, mobile apps) as they can be easily extracted.
Specific to OAuth 2.0
- Validate redirect URIs: Ensure that your registered redirect URIs are correct and specific, preventing authorization codes from being sent to malicious endpoints.
- Use PKCE (Proof Key for Code Exchange): For public clients (e.g., mobile apps, SPAs), implement PKCE to prevent authorization code interception attacks.
- Securely store tokens: Access tokens are short-lived, but refresh tokens (if used) are long-lived and must be stored securely, similar to API keys.
- Scope management: Request only the minimum necessary scopes from the user to perform your application's function. Clearly communicate to users what permissions your application is requesting.