Skip to main content

Authentication & Authorization

This guide covers authentication and authorization mechanisms for integrating with the SBM CRM Platform APIs.

Authentication Methods

The SBM CRM Platform supports multiple authentication methods depending on your use case:

  1. OAuth 2.0 - For user-facing applications
  2. API Keys - For server-to-server integrations
  3. JWT Tokens - For authenticated user sessions
  4. WeChat OAuth - For WeChat Mini Program integrations

OAuth 2.0 Flow

Authorization Code Flow

For web applications and mobile apps:

GET /oauth/authorize?
client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&response_type=code
&scope=read write
&state=RANDOM_STATE_STRING

Exchange Authorization Code for Token

POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code
&code=AUTHORIZATION_CODE
&redirect_uri=YOUR_REDIRECT_URI
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET

Response:

{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "def50200a1b2c3d4e5f6...",
"scope": "read write"
}

API Key Authentication

For server-to-server integrations, use API keys:

GET /api/v1/customers
Authorization: Bearer YOUR_API_KEY
X-API-Key: YOUR_API_KEY

Generating API Keys

API keys can be generated from the Admin Web App:

  1. Navigate to SettingsAPI Keys
  2. Click Create New API Key
  3. Set permissions and expiration
  4. Copy and securely store the key

Example API Key:

sk_live_51AbCdEfGhIjKlMnOpQrStUvWxYz1234567890

JWT Token Authentication

JWT tokens are used for authenticated user sessions:

Token Structure

{
"header": {
"alg": "HS256",
"typ": "JWT"
},
"payload": {
"sub": "user_12345",
"email": "user@example.com",
"role": "customer",
"tier": "gold",
"iat": 1609459200,
"exp": 1609462800
}
}

Using JWT Tokens

GET /api/v1/customers/me
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

WeChat OAuth Integration

For WeChat Mini Program authentication:

Step 1: Get WeChat Code

// In WeChat Mini Program
wx.login({
success: (res) => {
const code = res.code;
// Send code to your backend
}
});

Step 2: Exchange Code for Token

POST /api/v1/auth/wechat/login
Content-Type: application/json

{
"code": "WECHAT_CODE",
"app_id": "YOUR_WECHAT_APP_ID"
}

Response:

{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "user_12345",
"openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o",
"unionid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
"nickname": "User Nickname",
"avatar": "https://..."
}
}

Authorization & Permissions

Role-Based Access Control (RBAC)

The platform supports the following roles:

  • admin - Full system access
  • marketing - Campaign and promotion management
  • tenant - Tenant-specific data access
  • customer - Own profile and data access

Scope-Based Permissions

API scopes define what actions can be performed:

  • read - Read-only access
  • write - Create and update operations
  • admin - Administrative operations
  • analytics - Analytics and reporting access

Example: Checking Permissions

GET /api/v1/customers/12345
Authorization: Bearer TOKEN

# Requires: read scope
POST /api/v1/campaigns
Authorization: Bearer TOKEN

# Requires: write scope and marketing role

Token Refresh

Access tokens expire after 1 hour. Use refresh tokens to obtain new access tokens:

POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token
&refresh_token=REFRESH_TOKEN
&client_id=YOUR_CLIENT_ID
&client_secret=YOUR_CLIENT_SECRET

Error Handling

Invalid Token

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"error": "invalid_token",
"error_description": "The access token is invalid or expired"
}

Insufficient Permissions

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
"error": "insufficient_scope",
"error_description": "The request requires higher privileges"
}

Security Best Practices

  1. Never expose API keys in client-side code
  2. Use HTTPS for all API requests
  3. Store tokens securely (use secure storage, not localStorage for sensitive tokens)
  4. Implement token rotation for long-lived tokens
  5. Monitor API key usage for suspicious activity
  6. Use the principle of least privilege when assigning scopes

Code Examples

JavaScript/Node.js

const axios = require('axios');

// Using API Key
const apiClient = axios.create({
baseURL: 'https://api.sbmcrm.example.com/v1',
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type': 'application/json'
}
});

// Make authenticated request
async function getCustomer(customerId) {
try {
const response = await apiClient.get(`/customers/${customerId}`);
return response.data;
} catch (error) {
if (error.response?.status === 401) {
// Handle authentication error
console.error('Authentication failed');
}
throw error;
}
}

Python

import requests

# Using API Key
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}

# Make authenticated request
def get_customer(customer_id):
url = f'https://api.sbmcrm.example.com/v1/customers/{customer_id}'
response = requests.get(url, headers=headers)

if response.status_code == 401:
# Handle authentication error
raise Exception('Authentication failed')

return response.json()

cURL

# Using API Key
curl -X GET "https://api.sbmcrm.example.com/v1/customers/12345" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"