Skip to content
Last updated

This comprehensive guide covers all authentication methods supported by the PERS API, helping developers integrate secure access to the platform.


Authentication Overview

PERS supports multiple authentication methods designed to accommodate different integration patterns and use cases:

  • API Key Authentication - For business applications and server-to-server integration
  • JWT User Authentication - For end-user applications and authenticated user operations
  • Admin Authentication - For administrative operations and platform management
  • Mixed Authentication - Flexible endpoints supporting multiple authentication types

All authentication methods include built-in security features including rate limiting, request validation, and comprehensive audit logging.


API Key Authentication

Use Cases

  • Business applications integrating PERS into existing systems
  • Server-to-server API calls
  • Automated processes and background operations
  • Partner integrations and B2B scenarios

Implementation

Request Headers

Authorization: Bearer YOUR_API_KEY
X-Project-Key: your-project-key
Content-Type: application/json

Example Request

const response = await fetch('https://api.pers.ninja/v2/campaigns', {
  headers: {
    'Authorization': 'Bearer pk_live_abc123...',
    'X-Project-Key': 'pk_test_abc123_xyz789',
    'Content-Type': 'application/json'
  }
});

Security Features

  • Project Isolation: Each project key is automatically scoped to specific project data
  • Permission Validation: Project keys include built-in business permission validation
  • Rate Limiting: 10,000 requests per hour per project key
  • Request Logging: Comprehensive audit trails for all project key usage

Third-Party Token Exchange Authentication

Use Cases

  • Mobile applications integrating with external authentication providers
  • Web applications using third-party identity providers
  • User authentication through DFNS, Firebase, Auth0, Okta, or other JWT providers
  • Single Sign-On (SSO) integrations

Token Exchange Flow

PERS implements a secure token exchange pattern where third-party JWT tokens are verified and exchanged for PERS-native JWT tokens:

  1. External Provider Authentication: User authenticates with third-party provider
  2. Token Exchange Request: Client sends external JWT to PERS /auth/token endpoint
  3. Token Verification: PERS verifies the external JWT token with the provider
  4. User Resolution: PERS creates or updates user based on external identity
  5. PERS JWT Issuance: Returns PERS-native access and refresh tokens

Implementation

Token Exchange Request

POST /auth/token
X-Project-Key: your_project_key
Content-Type: application/json

{
  "authToken": "external_provider_jwt_token"
}

Example Integration

// Step 1: Get token from external provider (DFNS, Firebase, etc.)
const externalToken = await yourExternalProvider.authenticate();

// Step 2: Exchange for PERS tokens
const response = await fetch('https://api.pers.ninja/v2/auth/token', {
  method: 'POST',
  headers: {
    'X-Project-Key': 'pk_test_abc123_xyz789',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    authToken: externalToken
  })
});

const { user, accessToken, refreshToken } = await response.json();

// Step 3: Use PERS access token for API calls
const balanceResponse = await fetch('https://api.pers.ninja/v2/balance', {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  }
});

Supported External Providers

  • DFNS: Web3 authentication and wallet management
  • Firebase: Google's authentication platform
  • Auth0: Enterprise identity platform
  • Okta: Enterprise SSO provider
  • Custom JWT: Any compliant JWT provider

Security Features

  • External Token Verification: Validates JWT signatures against external provider
  • User Identity Resolution: Automatic user creation/update based on external identity
  • Project Isolation: All tokens scoped to specific project data
  • Refresh Token Support: Long-lived refresh tokens for seamless re-authentication

Admin Authentication

Use Cases

  • Platform administration and management
  • Tenant configuration and oversight
  • System monitoring and reporting
  • Administrative claim processing

Implementation

Firebase JWT Authentication

Admin authentication uses Firebase JWT tokens with elevated permissions:

// Admin authentication with Firebase JWT
const response = await fetch('https://api.pers.ninja/v2/admin/users', {
  headers: {
    'Authorization': 'Bearer firebase_jwt_token',
    'Content-Type': 'application/json'
  }
});

Security Features

  • Firebase Integration: Leverages Firebase authentication infrastructure
  • Elevated Permissions: Access to administrative operations and cross-tenant data
  • Audit Logging: Enhanced logging for all administrative operations
  • Multi-Factor Authentication: Supports MFA through Firebase configuration

Mixed Authentication Endpoints

Many PERS endpoints support multiple authentication methods, providing flexibility for different integration scenarios.

Example: File Upload Endpoint

The /files/entity-storage-url endpoint accepts all three authentication types:

Business Integration

// API Key authentication for business file uploads
const response = await fetch('https://api.pers.ninja/v2/files/entity-storage-url', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer pk_live_abc123...',
    'X-Project-Key': 'pk_live_abc123_xyz789',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    entityType: 'CAMPAIGN',
    operation: 'upload'
  })
});

User Integration (via Token Exchange)

// First exchange external token for PERS JWT
const authResponse = await fetch('https://api.pers.platform/auth/token', {
  method: 'POST',
  headers: {
    'X-API-Key': 'your_tenant_api_key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    authToken: 'external_provider_jwt_token'
  })
});
const { accessToken } = await authResponse.json();

// Then use PERS JWT for file uploads
const response = await fetch('https://api.pers.platform/files/entity-storage-url', {
  method: 'POST', 
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    entityType: 'USER', // Automatically restricted for user auth
    operation: 'upload'
  })
});

Admin Integration

// Admin authentication for administrative file operations
const response = await fetch('https://api.pers.ninja/v2/files/entity-storage-url', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer firebase_admin_jwt...',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    entityType: 'PLATFORM', 
    operation: 'upload'
  })
});

Counterfactual Wallets & User Signing

PERS implements an innovative counterfactual wallet system that provides users with blockchain addresses before their first transaction. This approach combines the convenience of immediate wallet availability with secure, user-controlled transaction signing when needed.

For comprehensive information about counterfactual wallets, signing accounts, and implementation details, please refer to our dedicated guide:

Counterfactual Wallets & Signing Accounts Guide →

Quick Overview

  • Immediate Wallet Creation: Users receive wallet addresses instantly upon account creation
  • Zero Upfront Costs: No blockchain fees required for initial setup
  • Progressive Enhancement: Blockchain features unlock as users engage more deeply
  • Multiple Signing Options: Support for PERS native signer and external wallet providers
  • Enterprise Security: Hardware-backed security with biometric authentication support

Integration Benefits

  • Simplified Onboarding: Users can participate in loyalty programs without blockchain complexity
  • Cost Optimization: Only active users incur deployment costs
  • Familiar UX: Authentication feels like traditional app login flows
  • Developer Friendly: Unified API regardless of chosen signing provider

Error Handling

PERS API uses a structured error handling system with security-first classification and correlation IDs for traceability.

Error Response Structure

All API errors return structured responses that include correlation IDs and security-filtered messages:

interface StructuredError {
  message: string;           // Security-filtered user-friendly message
  code: string;             // Error code (e.g., "AUTHENTICATION_REQUIRED")
  timestamp?: string;       // ISO timestamp
  category: ErrorCategory;  // Error classification 
  correlationId?: string;   // Request traceability ID
  details?: Record<string, any>; // Additional context (non-sensitive)
  userMessage?: string;     // User-facing description
  retryable: boolean;       // Whether operation can be retried
}

Authentication Error Responses

Invalid API Key (401 Unauthorized)

{
  "message": "Authentication required",
  "code": "AUTHENTICATION_REQUIRED", 
  "category": "SECURITY",
  "timestamp": "2024-01-15T10:30:00Z",
  "correlationId": "req-abc123",
  "userMessage": "Please provide valid authentication credentials",
  "retryable": false
}

Expired JWT Token (401 Unauthorized)

{
  "message": "Authentication token has expired",
  "code": "AUTHENTICATION_REQUIRED",
  "category": "SECURITY", 
  "timestamp": "2024-01-15T10:30:00Z",
  "correlationId": "req-def456",
  "userMessage": "Your session has expired. Please authenticate again",
  "retryable": false
}

Insufficient Permissions (403 Forbidden)

{
  "message": "Authorization failed for requested resource",
  "code": "AUTHORIZATION_FAILED",
  "category": "SECURITY",
  "timestamp": "2024-01-15T10:30:00Z",
  "correlationId": "req-ghi789",
  "userMessage": "You do not have permission to access this resource",
  "retryable": false
}

Rate Limit Exceeded (429 Too Many Requests)

{
  "message": "Request rate limit exceeded",
  "code": "RATE_LIMIT_EXCEEDED", 
  "category": "RATE_LIMIT",
  "timestamp": "2024-01-15T10:30:00Z",
  "correlationId": "req-jkl012",
  "userMessage": "Too many requests. Please try again later",
  "retryable": true,
  "details": {
    "retryAfter": 3600
  }
}

Error Categories & HTTP Status Mapping

PERS uses predefined error categories that map to specific HTTP status codes:

CategoryHTTP StatusDescriptionRetryable
VALIDATION400Invalid request data or formatNo
SECURITY403Authentication/authorization failuresNo
DOMAIN_RULE422Business logic validation errorsNo
RATE_LIMIT429Request rate limitingYes
INFRASTRUCTURE503External service failuresYes

Security Features

  • Message Filtering: System error details are never exposed to API consumers
  • Correlation IDs: Every error includes a correlation ID for support traceability
  • Structured Logging: All errors are logged with full context for debugging
  • Category Classification: Consistent error categorization across all domains

Security Best Practices

API Key Security

  • Environment Variables: Store API keys in secure environment variables, never in source code
  • Key Rotation: Regularly rotate API keys and update applications accordingly
  • Scope Limitation: Use API keys with minimal required permissions for each integration
  • Network Security: Restrict API key usage to authorized IP addresses when possible

JWT Token Security

  • Secure Storage: Store JWT tokens securely on client devices using appropriate security mechanisms
  • Token Expiration: Implement automatic token refresh before expiration
  • HTTPS Only: Always use HTTPS for requests containing JWT tokens
  • Logout Handling: Properly clear tokens on user logout

General Security

  • Request Validation: Validate all request data before sending to PERS APIs
  • Error Handling: Implement comprehensive error handling without exposing sensitive information
  • Audit Logging: Maintain logs of API usage for security monitoring and compliance
  • Network Monitoring: Monitor API traffic patterns for unusual activity

Getting Started

  1. Choose Authentication Method: Select the appropriate authentication type for your use case
  2. Obtain Credentials: Contact PERS support to obtain API keys or configure JWT authentication
  3. Implement Authentication: Add authentication headers to your API requests
  4. Test Integration: Use development/sandbox environment to validate authentication flows
  5. Monitor Usage: Implement logging and monitoring for production deployments

� PERS Shared Library

@explorins/pers-shared

The official TypeScript library providing type-safe contracts and DTOs for PERS API integration.

Installation

npm install @explorins/pers-shared

Library Information

  • Package Name: @explorins/pers-shared
  • Current Version: 2.1.9
  • Registry: npmjs.org
  • License: MIT
  • Maintainer: eXplorins Development Team

What's Included

  • DTOs: Complete type definitions for all API request/response objects
  • Interfaces: TypeScript contracts for authentication, users, campaigns, transactions
  • Types & Enums: Authentication types, error codes, transaction statuses
  • Value Objects: Immutable data structures like Address, StructuredError

Usage Examples

Backend/Node.js Integration
import { 
  UserDTO, 
  TransactionStatus, 
  AuthenticationRequiredError,
  PasskeysAuthRequestDTO 
} from '@explorins/pers-shared';

// Type-safe API requests
const authRequest: PasskeysAuthRequestDTO = {
  authToken: "external_provider_jwt_token"
};

// Structured error handling
try {
  const user = await authenticate(authRequest);
} catch (error) {
  if (error instanceof AuthenticationRequiredError) {
    // Handle authentication error
  }
}
Frontend/Browser Integration
// Browser-optimized import for smaller bundle size
import { UserDTO, CampaignDTO } from '@explorins/pers-shared/browser';

// Type-safe API client
interface PERSApiClient {
  authenticate(request: PasskeysAuthRequestDTO): Promise<UserAuthResponseDTO>;
  getBalance(userId: string): Promise<UserTokenBalancesDTO>;
}

Build Configurations

  • CommonJS: Backend compatibility with NestJS/Swagger support
  • ESM: Frontend optimization with tree-shaking
  • TypeScript Declarations: Full type support for IDEs

Key Features

  • Zero Dependencies: Pure TypeScript contracts with no runtime dependencies
  • Dual Build System: Supports both CommonJS (Node.js) and ESM (browsers)
  • Type Safety: Comprehensive TypeScript definitions for all PERS APIs
  • Authentication Types: All authentication DTOs and error classes included
  • Browser Optimized: Separate browser entry point for smaller bundles

�🚀 Getting Started

  1. Install PERS Library: npm install @explorins/pers-shared for type-safe integration
  2. Choose Authentication Method: Select the appropriate authentication type for your use case
  3. Obtain Credentials: Contact PERS support to obtain API keys or configure JWT authentication
  4. Implement Authentication: Add authentication headers and use library types for requests
  5. Test Integration: Use development/sandbox environment to validate authentication flows
  6. Monitor Usage: Implement logging and monitoring for production deployments

For additional support with authentication implementation, contact our integration team or refer to the complete API documentation.