Authentication

The Alifshop API uses multiple authentication methods to ensure secure access to our platform. Choose the authentication method that best fits your application type and security requirements.

Authentication Methods

The Alifshop API supports several authentication methods depending on your use case:

API Key Authentication

  • Best for: Server-to-server integrations, backend applications
  • Pros: Simple to implement, no user interaction required
  • Cons: Limited to application-level permissions

OAuth 2.0

  • Best for: Applications that access user data, web and mobile apps
  • Pros: User consent, granular permissions, secure token management
  • Cons: More complex implementation

Session-based Authentication

  • Best for: Web applications with user sessions
  • Pros: Standard web authentication flow
  • Cons: Requires session management

API Key Authentication

API keys are the simplest way to authenticate with the Alifshop API. They're perfect for server-to-server integrations and backend applications.

Getting Your API Key

  1. Sign up for a developer account at developer.alifshop.af
  2. Create a new application in your developer dashboard
  3. Copy your API key from the application settings

API Key Format

API keys follow a specific format to identify their type and environment:

ak_test_1234567890abcdef    # Test environment key
ak_live_1234567890abcdef    # Production environment key

Using API Keys

Include your API key in the Authorization header with the Bearer scheme:

curl -X GET "https://api.alifshop.af/v1/catalog/categories" \
  -H "Authorization: Bearer ak_live_your_api_key_here" \
  -H "Content-Type: application/json"

API Key Scopes

API keys can be configured with different permission scopes:

  • catalog:read - Read access to product catalog
  • catalog:write - Write access to product catalog
  • cart:read - Read access to shopping carts
  • cart:write - Write access to shopping carts
  • orders:read - Read access to orders
  • orders:write - Write access to orders
  • marketing:read - Read access to marketing data
  • marketing:write - Write access to marketing campaigns
  • admin:read - Read access to admin data
  • admin:write - Write access to admin functions

OAuth 2.0

OAuth 2.0 is the recommended authentication method for applications that need to access user-specific data or act on behalf of users.

Supported OAuth 2.0 Flows

Authorization Code Flow

Best for web applications with a backend server:

GET https://auth.alifshop.af/oauth/authorize?
  response_type=code&
  client_id=your_client_id&
  redirect_uri=https://yourapp.com/callback&
  scope=catalog:read cart:write orders:read&
  state=random_state_string

Client Credentials Flow

For server-to-server authentication without user context:

curl -X POST "https://auth.alifshop.af/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=your_client_id" \
  -d "client_secret=your_client_secret" \
  -d "scope=catalog:read"

Implicit Flow (Deprecated)

Authorization Code Flow Implementation

Step 1: Redirect User to Authorization Server

const authUrl = new URL('https://auth.alifshop.af/oauth/authorize');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', 'your_client_id');
authUrl.searchParams.set('redirect_uri', 'https://yourapp.com/callback');
authUrl.searchParams.set('scope', 'catalog:read cart:write orders:read');
authUrl.searchParams.set('state', generateRandomState());

window.location.href = authUrl.toString();

Step 2: Exchange Authorization Code for Token

curl -X POST "https://auth.alifshop.af/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code" \
  -d "code=authorization_code_here" \
  -d "client_id=your_client_id" \
  -d "client_secret=your_client_secret" \
  -d "redirect_uri=https://yourapp.com/callback"

Step 3: Token Response

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "def50200a1b2c3d4e5f6...",
  "scope": "catalog:read cart:write orders:read"
}

Using Access Tokens

Include the access token in the Authorization header:

curl -X GET "https://api.alifshop.af/v1/catalog/products" \
  -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."

Token Refresh

When your access token expires, use the refresh token to get a new one:

curl -X POST "https://auth.alifshop.af/oauth/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=refresh_token" \
  -d "refresh_token=def50200a1b2c3d4e5f6..." \
  -d "client_id=your_client_id" \
  -d "client_secret=your_client_secret"

Request Headers

Required Headers

All API requests must include these headers:

Authorization: Bearer your_token_here
Content-Type: application/json
Accept: application/json

Optional Headers

Additional headers that can improve your API experience:

X-Request-ID: unique_request_identifier
X-API-Version: v1
X-Client-Name: your_app_name
X-Client-Version: 1.0.0
User-Agent: YourApp/1.0.0 (https://yourwebsite.com)

Regional Headers

For region-specific functionality:

X-Alifshop-Region: afghanistan
Accept-Language: fa-AF,en-US
X-Currency: AFN
X-Timezone: Asia/Kabul

Idempotency

For write operations, use idempotency keys to safely retry requests:

Idempotency-Key: unique_operation_identifier

Error Handling

Common Authentication Errors

401 Unauthorized

Your API key or access token is invalid or expired:

{
  "error": {
    "code": "unauthorized",
    "message": "Invalid or expired authentication token",
    "type": "authentication_error",
    "details": {
      "reason": "token_expired",
      "expires_at": "2024-01-15T12:00:00Z"
    }
  }
}

403 Forbidden

Your API key doesn't have the required permissions:

{
  "error": {
    "code": "insufficient_permissions",
    "message": "Your API key doesn't have permission to access this resource",
    "type": "authorization_error",
    "details": {
      "required_scopes": ["catalog:write"],
      "current_scopes": ["catalog:read"]
    }
  }
}

429 Too Many Requests

You've exceeded the rate limit:

{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Too many requests. Please slow down.",
    "type": "rate_limit_error",
    "details": {
      "retry_after": 60,
      "limit": 1000,
      "remaining": 0,
      "reset_at": "2024-01-15T12:00:00Z"
    }
  }
}

Error Handling Best Practices

Implement Retry Logic

async function makeAuthenticatedRequest(url, options = {}) {
  const maxRetries = 3;
  let retries = 0;
  
  while (retries < maxRetries) {
    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          'Authorization': `Bearer ${getAccessToken()}`,
          'Content-Type': 'application/json',
          ...options.headers
        }
      });
      
      if (response.status === 401) {
        // Token expired, try to refresh
        await refreshAccessToken();
        retries++;
        continue;
      }
      
      if (response.status === 429) {
        // Rate limited, wait and retry
        const retryAfter = response.headers.get('Retry-After');
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        retries++;
        continue;
      }
      
      return response;
    } catch (error) {
      retries++;
      if (retries >= maxRetries) throw error;
    }
  }
}

Best Practices

Security

  • Store credentials securely using environment variables or secure configuration management
  • Use HTTPS only for all API requests
  • Rotate API keys regularly (at least every 90 days)
  • Implement proper token refresh logic for OAuth applications
  • Never log authentication tokens in application logs
  • Use the principle of least privilege when requesting scopes

Performance

  • Cache tokens appropriately but respect expiration times
  • Implement exponential backoff for rate limit errors
  • Use connection pooling for high-volume applications
  • Monitor token usage and refresh patterns

Monitoring

  • Track authentication failures and investigate patterns
  • Monitor token expiration and refresh success rates
  • Set up alerts for authentication-related errors
  • Log authentication events (without sensitive data) for audit purposes

Example Implementation

Here's a complete example in JavaScript:

class AlifshopAuthClient {
  constructor(clientId, clientSecret, apiKey) {
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.apiKey = apiKey;
    this.accessToken = null;
    this.refreshToken = null;
    this.baseURL = 'https://api.alifshop.af/v1';
  }
  
  async makeRequest(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    
    const headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      ...options.headers
    };
    
    // Use API key or access token
    if (this.accessToken) {
      headers.Authorization = `Bearer ${this.accessToken}`;
    } else if (this.apiKey) {
      headers.Authorization = `Bearer ${this.apiKey}`;
    }
    
    const response = await fetch(url, {
      ...options,
      headers
    });
    
    if (response.status === 401 && this.refreshToken) {
      await this.refreshAccessToken();
      return this.makeRequest(endpoint, options);
    }
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error: ${error.error.message}`);
    }
    
    return response.json();
  }
  
  async refreshAccessToken() {
    const response = await fetch('https://auth.alifshop.af/oauth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        grant_type: 'refresh_token',
        refresh_token: this.refreshToken,
        client_id: this.clientId,
        client_secret: this.clientSecret
      })
    });
    
    const tokens = await response.json();
    this.accessToken = tokens.access_token;
    this.refreshToken = tokens.refresh_token;
  }
}