This comprehensive guide covers all authentication methods supported by the PERS API, helping developers integrate secure access to the platform.
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.
- Business applications integrating PERS into existing systems
- Server-to-server API calls
- Automated processes and background operations
- Partner integrations and B2B scenarios
Authorization: Bearer YOUR_API_KEY
X-Project-Key: your-project-key
Content-Type: application/jsonconst 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'
}
});- 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
- 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
PERS implements a secure token exchange pattern where third-party JWT tokens are verified and exchanged for PERS-native JWT tokens:
- External Provider Authentication: User authenticates with third-party provider
- Token Exchange Request: Client sends external JWT to PERS
/auth/tokenendpoint - Token Verification: PERS verifies the external JWT token with the provider
- User Resolution: PERS creates or updates user based on external identity
- PERS JWT Issuance: Returns PERS-native access and refresh tokens
POST /auth/token
X-Project-Key: your_project_key
Content-Type: application/json
{
"authToken": "external_provider_jwt_token"
}// 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'
}
});- 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
- 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
- Platform administration and management
- Tenant configuration and oversight
- System monitoring and reporting
- Administrative claim processing
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'
}
});- 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
Many PERS endpoints support multiple authentication methods, providing flexibility for different integration scenarios.
The /files/entity-storage-url endpoint accepts all three authentication types:
// 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'
})
});// 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 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'
})
});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 →
- 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
- 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
PERS API uses a structured error handling system with security-first classification and correlation IDs for traceability.
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
}{
"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
}{
"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
}{
"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
}{
"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
}
}PERS uses predefined error categories that map to specific HTTP status codes:
| Category | HTTP Status | Description | Retryable |
|---|---|---|---|
VALIDATION | 400 | Invalid request data or format | No |
SECURITY | 403 | Authentication/authorization failures | No |
DOMAIN_RULE | 422 | Business logic validation errors | No |
RATE_LIMIT | 429 | Request rate limiting | Yes |
INFRASTRUCTURE | 503 | External service failures | Yes |
- 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
- 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
- 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
- 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
- Choose Authentication Method: Select the appropriate authentication type for your use case
- Obtain Credentials: Contact PERS support to obtain API keys or configure JWT authentication
- Implement Authentication: Add authentication headers to your API requests
- Test Integration: Use development/sandbox environment to validate authentication flows
- Monitor Usage: Implement logging and monitoring for production deployments
The official TypeScript library providing type-safe contracts and DTOs for PERS API integration.
npm install @explorins/pers-shared- Package Name:
@explorins/pers-shared - Current Version:
2.1.9 - Registry: npmjs.org
- License: MIT
- Maintainer: eXplorins Development Team
- 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
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
}
}// 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>;
}- CommonJS: Backend compatibility with NestJS/Swagger support
- ESM: Frontend optimization with tree-shaking
- TypeScript Declarations: Full type support for IDEs
- 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
- Install PERS Library:
npm install @explorins/pers-sharedfor type-safe integration - Choose Authentication Method: Select the appropriate authentication type for your use case
- Obtain Credentials: Contact PERS support to obtain API keys or configure JWT authentication
- Implement Authentication: Add authentication headers and use library types for requests
- Test Integration: Use development/sandbox environment to validate authentication flows
- 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.