Registering and managing keys
Registering an app on the Daraja portal and a case study in keeping keys safe.
Real-world System / Production Context: Registering an Application on the Daraja Portal
To ground this theoretical understanding in a concrete, real-world scenario, let's walk through the process of registering a new application on the Safaricom Daraja Developer Portal to obtain these crucial credentials. This process is the initial step for any developer or business aiming to integrate with Mpesa.
The Safaricom Daraja Developer Portal (developer.safaricom.co.ke) is the central hub where developers manage their Mpesa integrations. It provides tools for application registration, credential management, API documentation, and testing.
Step-by-step process of registering an application:
- Account Creation/Login: A developer first needs to create an account or log in to the Daraja Developer Portal. This typically involves providing an email address, setting a password, and sometimes verifying a phone number.
- Navigate to "My Apps": Once logged in, the developer navigates to a section usually labeled "My Apps" or "Applications." This section lists all applications previously registered by the user and provides an option to create a new one.
- Create New App: The developer initiates the process of creating a new application. This usually involves clicking a button like "Add New App" or "Create Application."
- Provide Application Details: The portal prompts for basic information about the application:
- App Name: A descriptive name for the application (e.g., "My E-commerce Store Payments," "Utility Bill Payment System").
- App Description: A brief explanation of the application's purpose.
- Environment Selection: This is a critical choice. The developer must select whether the application is for the Sandbox environment or the Production environment.
- For initial development and testing, "Sandbox" is selected.
- For live operations, "Production" is selected, which often triggers additional requirements and an approval workflow.
- API Selection (Optional but common): Some portals might ask which specific APIs the application intends to use (e.g., Mpesa Express, B2C, C2B). This helps in configuring appropriate permissions.
- Submission and Credential Generation:
- For Sandbox Applications: Upon submitting the details for a sandbox application, the Daraja portal typically generates the Consumer Key and Consumer Secret almost instantly. These are displayed directly on the screen and are also usually accessible from the application's details page within "My Apps." The developer is advised to copy and securely store these credentials immediately.
- For Production Applications: Submitting a production application request initiates an approval workflow. The developer might need to provide additional business documentation (e.g., business registration certificate, Mpesa Paybill/Buy Goods number, bank details). Safaricom's team reviews the application. Once approved, the production Consumer Key and Consumer Secret are made available on the portal. This process can take several business days.
Obtaining the Consumer Key and Secret: After an application is successfully registered (either sandbox or production), navigating to its details page within the "My Apps" section of the Daraja Developer Portal will display the generated Consumer Key and Consumer Secret. The Consumer Secret is often masked for security reasons and may require a click to reveal it. It is crucial to copy both values accurately.
The distinction between sandbox and production application registration: As highlighted earlier, the registration process itself reinforces the distinction. Sandbox registration is streamlined for rapid development, while production registration is more stringent, reflecting the real financial implications of live API access. A developer will typically register two separate applications: one for sandbox testing and another for production deployment, each with its own unique set of Consumer Key and Secret.
The concept of "My Apps" on the portal: The "My Apps" section serves as a dashboard for developers. Here, they can:
- View a list of all their registered applications.
- Access the Consumer Key and Secret for each application.
- Monitor API usage statistics.
- Manage application settings (e.g., callback URLs, if applicable for other OAuth flows).
- Initiate the process to revoke or regenerate credentials (though regeneration of Consumer Secret is more common than Consumer Key).
This hands-on process of registering an application and obtaining credentials is the gateway to interacting with the Daraja API. It underscores that the Consumer Key and Secret are not abstract concepts but tangible identifiers and secrets that developers must actively manage.
Deep-dive Analysis Block: Case Study - Secure Credential Management for a Daraja Integration
This case study explores the practical challenges and best practices for securely managing and utilizing Consumer Key and Secret within a hypothetical e-commerce platform integrating with Mpesa for payment processing.
Scenario: "SwiftCart" is a rapidly growing e-commerce platform that needs to integrate Mpesa as a primary payment method. Their backend is built using Node.js and deployed on a cloud platform (e.g., AWS). They need to implement Mpesa Express (STK Push) for customer payments and C2B (Customer to Business) for receiving direct payments to their Mpesa Paybill.
Problem: SwiftCart's development team needs to ensure that their Mpesa Daraja integration is secure, resilient, and compliant. Specifically, they face the challenge of securely managing their Daraja Consumer Key and Secret throughout the development lifecycle, from sandbox testing to production deployment. A credential compromise could lead to unauthorized transactions, financial losses, and reputational damage.
Solution Walkthrough:
Initial Registration on Daraja Portal (Sandbox):
- The SwiftCart lead developer logs into the Safaricom Daraja Developer Portal.
- They navigate to "My Apps" and click "Add New App."
- They name the app "SwiftCart Sandbox" and select "Sandbox" as the environment.
- Upon submission, the portal instantly generates a Sandbox Consumer Key and a Sandbox Consumer Secret.
- Action: The developer immediately copies these two values.
Developing and Testing with Sandbox Credentials:
- Credential Storage (Development): For local development, the developers store the Sandbox Consumer Key and Secret in a
.envfile (a common practice for environment variables) in the project root, which is explicitly excluded from version control (e.g., via.gitignore).Text# .env (NOT committed to Git) DARAJA_CONSUMER_KEY="sb_CK_xxxxxxxxxxxxxxxxxxxxxxxxxxxx" DARAJA_CONSUMER_SECRET="sb_CS_yyyyyyyyyyyyyyyyyyyyyyyyyyyy" - Code Implementation (Node.js example for token generation):javascript
// app.js (simplified for illustration) require('dotenv').config(); // Loads .env variables const axios = require('axios'); const sandboxConsumerKey = process.env.DARAJA_CONSUMER_KEY; const sandboxConsumerSecret = process.env.DARAJA_CONSUMER_SECRET; const sandboxBaseUrl = "https://sandbox.safaricom.co.ke"; // Sandbox API base URL async function getSandboxAccessToken() { if (!sandboxConsumerKey || !sandboxConsumerSecret) { throw new Error("Sandbox Consumer Key or Secret not found in environment variables."); } const authString = Buffer.from(`${sandboxConsumerKey}:${sandboxConsumerSecret}`).toString('base64'); try { const response = await axios.get(`${sandboxBaseUrl}/oauth/v1/generate?grant_type=client_credentials`, { headers: { 'Authorization': `Basic ${authString}` } }); console.log("Got a sandbox access token."); // never log the token itself return response.data.access_token; } catch (error) { console.error("Error getting sandbox access token:", error.response ? error.response.data : error.message); throw error; } } // Example usage during development // getSandboxAccessToken().then(token => { // // Use token for other sandbox API calls // }).catch(err => console.error("Failed to get token:", err)); - Testing: SwiftCart's QA team uses the sandbox environment to simulate customer payments, verify STK Push prompts, and confirm transaction callbacks. They use dummy Mpesa numbers provided by Daraja for testing.
- Credential Storage (Development): For local development, the developers store the Sandbox Consumer Key and Secret in a
Transitioning to Production:
- New Production Application Registration: Once sandbox testing is complete and stable, the SwiftCart lead developer returns to the Daraja Developer Portal.
- They open Go Live on the portal, verify their Paybill with the one-time code Safaricom sends, and choose the products they need. Some products, such as C2B external validation, need a separate request to Safaricom.
- Action: The portal issues a Production Consumer Key and Production Consumer Secret, and the M-Pesa Express passkey arrives by email. These are distinct from the sandbox keys.
- Action: The developer copies these production credentials.
Secure Storage of Credentials (Production Environment):
- Cloud Secret Management: SwiftCart, being on AWS, decides to use AWS Secrets Manager for storing their production credentials.
- They create a new secret in Secrets Manager, storing
DARAJA_CONSUMER_KEYandDARAJA_CONSUMER_SECRETas key-value pairs. The names are the same as in development; only the values and where they live change, so the code doesn't need a separate path for production. - Why: Secrets Manager encrypts the secrets at rest and in transit, provides fine-grained access control (IAM policies), and supports automatic rotation.
- They create a new secret in Secrets Manager, storing
- Environment Variables (Deployment): When deploying the Node.js application to their AWS EC2 instances or AWS Lambda functions, they configure the deployment pipeline to retrieve these secrets from AWS Secrets Manager at runtime and inject them as environment variables into the application's process. This ensures the secrets are never hardcoded or stored directly on the server's file system.Text
// Example of how environment variables would be set in production // (This is handled by the deployment pipeline interacting with Secrets Manager) // process.env.DARAJA_CONSUMER_KEY = "prod_CK_xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // process.env.DARAJA_CONSUMER_SECRET = "prod_CS_yyyyyyyyyyyyyyyyyyyyyyyyyyyy"; - Code Adaptation for Production: The application code is designed to dynamically load credentials based on the environment.javascript
// app.js (simplified for illustration, production logic) require('dotenv').config(); // Still useful for local dev, but production env vars take precedence const axios = require('axios'); // Assume a mechanism to load secrets from AWS Secrets Manager or directly from env vars in production const consumerKey = process.env.DARAJA_CONSUMER_KEY; const consumerSecret = process.env.DARAJA_CONSUMER_SECRET; const productionBaseUrl = "https://api.safaricom.co.ke"; // Production API base URL async function getProductionAccessToken() { if (!consumerKey || !consumerSecret) { throw new Error("Production Consumer Key or Secret not found in environment variables."); } const authString = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64'); try { const response = await axios.get(`${productionBaseUrl}/oauth/v1/generate?grant_type=client_credentials`, { headers: { 'Authorization': `Basic ${authString}` } }); console.log("Got a production access token."); // never log the token itself return response.data.access_token; } catch (error) { console.error("Error getting production access token:", error.response ? error.response.data : error.message); throw error; } }
- Cloud Secret Management: SwiftCart, being on AWS, decides to use AWS Secrets Manager for storing their production credentials.
Access Control for Credentials:
- Principle of Least Privilege: Only specific IAM roles (e.g., the role assigned to the EC2 instance running the SwiftCart backend) are granted permission to retrieve the Daraja production secrets from AWS Secrets Manager. Developers do not have direct access to production secrets in plain text.
- Auditing: AWS CloudTrail logs all access attempts to Secrets Manager, providing an audit trail for security monitoring.
Rotation of Credentials:
- SwiftCart configures AWS Secrets Manager to automatically rotate the Daraja Production Consumer Secret periodically (e.g., every 90 days).
- Mechanism: Secrets Manager invokes a Lambda function that interacts with the Daraja Developer Portal's API (if available for programmatic rotation) or guides a manual rotation process. The Lambda function generates a new secret on Daraja, updates Secrets Manager, and then updates the application's configuration if necessary.
- Why: Regular rotation minimizes the impact of a potential secret compromise, as an old, leaked secret would quickly become invalid.
Impact of Credential Compromise (Mitigation):
- If a production Consumer Secret were compromised, the attacker could potentially generate access tokens and initiate unauthorized transactions.
- SwiftCart's Mitigation:
- Immediate Rotation: The security team would immediately rotate the compromised secret via the Daraja portal and Secrets Manager.
- Monitoring: Enhanced monitoring for unusual API activity (e.g., high transaction volumes from unexpected IPs) would be triggered.
- Incident Response: A predefined incident response plan would be activated to assess the damage and notify relevant stakeholders.
This case study demonstrates how a real-world application manages its Daraja Consumer Key and Secret, emphasizing the transition from sandbox to production, the importance of secure storage solutions, and proactive security measures like access control and credential rotation.