Skip to content

Authentication

Overview

Pocketbook supports multiple authentication methods to fit different use cases. Choose the method that best suits your application:

MethodUse CaseLifespanSetup
Wallet SignatureWeb apps, user sessions24 hours (JWT)Connect wallet → Sign message
API KeysServer-to-server, automationPersistentDashboard → Generate key
JWT TokensMobile apps, SPAs24 hoursExchange wallet signature

Quick Start: Wallet Authentication

Perfect for web applications where users have wallets.

Step 1: Connect Wallet

javascript
import { ethers } from 'ethers';

// Connect to MetaMask
const provider = new ethers.BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const signer = await provider.getSigner();
const address = await signer.getAddress();

console.log('Connected:', address);

Step 2: Sign Authentication Message

javascript
// Generate authentication message
const timestamp = Math.floor(Date.now() / 1000);
const message = `Authenticate with Pocketbook: ${timestamp}`;

// Sign message
const signature = await signer.signMessage(message);

Step 3: Get JWT Token

javascript
// Exchange signature for JWT
const response = await fetch('https://api.pocketbook.studio/api/certificate/auth', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    signature,
    address,
    message,
    timestamp: timestamp.toString()
  })
});

const data = await response.json();
const token = data.data.token;

// Store token for future requests
localStorage.setItem('pocketbook_token', token);

Step 4: Use Token for API Requests

javascript
const token = localStorage.getItem('pocketbook_token');

const response = await fetch('https://api.pocketbook.studio/api/certificate/create', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'My Certificate',
    description: 'Certificate description',
    imageUrl: 'https://example.com/image.png'
  })
});

Quick Start: API Keys

Perfect for backend services and automation.

Step 1: Create API Key

  1. Log in to pocketbook.studio
  2. Navigate to SettingsAPI Keys (Enterprise plan required)
  3. Click Create New API Key
  4. Configure scopes and rate limits
  5. Copy and securely store the key

Step 2: Use API Key

javascript
// Node.js example
const fetch = require('node-fetch');

const API_KEY = process.env.POCKETBOOK_API_KEY;

const response = await fetch('https://api.pocketbook.studio/api/certificate/create', {
  method: 'POST',
  headers: {
    'x-api-key': API_KEY,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'My Certificate',
    description: 'Certificate description',
    imageUrl: 'https://example.com/image.png'
  })
});

const data = await response.json();
console.log('Certificate created:', data);

Authentication Flow

Wallet Signature Flow

User          Wallet        Pocketbook API
  │              │                │
  ├─Connect──────▶               │
  │              │                │
  ├─Request──────▶               │
  │   Sign       │                │
  │              │                │
  │◀─Signature───┤                │
  │              │                │
  ├─Submit────────────────────────▶
  │ {signature, address, message} │
  │              │                │
  │              │    Verify       │
  │              │   Signature     │
  │              │        ↓        │
  │◀─────────────────JWT Token────┤
  │              │                │

API Key Flow

Backend Service      Pocketbook API
      │                    │
      ├─Request────────────▶
      │ {x-api-key: KEY}   │
      │                    │
      │         Verify Key  │
      │              ↓      │
      │◀─────Response───────┤
      │                    │

Security Best Practices

API Key Security

DO:

  • Store API keys in environment variables
  • Use different keys for dev/staging/prod
  • Rotate keys regularly (every 90 days)
  • Use minimal scopes required
  • Monitor key usage
  • Revoke compromised keys immediately

DON'T:

  • Commit keys to version control
  • Share keys via email or chat
  • Use production keys in development
  • Embed keys in client-side code
  • Log keys in error messages

JWT Token Security

DO:

  • Store tokens securely (httpOnly cookies preferred)
  • Implement token refresh before expiry
  • Clear tokens on logout
  • Use HTTPS for all requests
  • Validate tokens on each request

DON'T:

  • Store tokens in localStorage (if handling sensitive data)
  • Share tokens between users
  • Ignore expiration
  • Include tokens in URLs
  • Log tokens in analytics

Wallet Security

DO:

  • Verify message format before signing
  • Check timestamp is recent (< 5 minutes)
  • Display message content to users
  • Use secure wallet providers
  • Implement wallet connection timeout

DON'T:

  • Sign messages without reading
  • Reuse signatures
  • Accept old timestamps
  • Trust client-provided data

Environment Setup

Create a .env file in your project:

bash
# API Configuration
POCKETBOOK_API_KEY=pk_your_api_key_here
POCKETBOOK_API_URL=https://api.pocketbook.studio/api

# JWT Configuration (if storing tokens server-side)
JWT_SECRET=your_jwt_secret
JWT_EXPIRY=24h

# Wallet Configuration
ETHEREUM_RPC_URL=https://polygon-rpc.com

Error Handling

Common Authentication Errors

javascript
try {
  const response = await fetch(url, options);
  const data = await response.json();

  if (!response.ok) {
    switch (response.status) {
      case 401:
        console.error('Authentication failed - check credentials');
        // Re-authenticate user
        break;
      case 403:
        console.error('Insufficient permissions');
        // Check API key scopes
        break;
      case 429:
        console.error('Rate limit exceeded');
        // Implement exponential backoff
        break;
      default:
        console.error('Request failed:', data.error);
    }
  }
} catch (error) {
  console.error('Network error:', error);
}

Testing Authentication

Test Wallet Authentication

bash
# Using curl with JWT token
curl -X POST https://api.pocketbook.studio/api/certificate/create \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test Certificate",
    "description": "Testing authentication",
    "imageUrl": "https://example.com/image.png"
  }'

Test API Key Authentication

bash
# Using curl with API key
curl -X POST https://api.pocketbook.studio/api/certificate/create \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test Certificate",
    "description": "Testing authentication",
    "imageUrl": "https://example.com/image.png"
  }'

Next Steps

Choose your learning path:

For Web Developers

Quick Start Guide - Build your first integration → Certificate Creation - Create certificates

For Backend Developers

API Authentication - Detailed auth documentation → API Overview - Explore all endpoints

For Enterprise

Enterprise Overview - Advanced features → API Keys - Key management


Need Help?

Released under the MIT License.