Skip to Content
GuidesAuthentication

Last Updated: 1/27/2026


Authentication

Learn how to authenticate with the Example API.

Authentication Methods

MethodUse CaseSecurity
API KeyServer-side appsHigh
OAuth2User authorizationHigh
JWTStateless authMedium

:::warning API keys should only be used in server-side code. Never expose them in browsers. :::

API Key Authentication

import { createClient } from '@example/sdk'; const client = createClient({ apiKey: process.env.EXAMPLE_API_KEY!, }); // All requests are automatically authenticated const users = await client.users.list();

Key Types

// Live key - for production const liveKey = 'sk_live_abc123...'; // Test key - for development const testKey = 'sk_test_xyz789...';

:::tip Use test keys during development. They have relaxed rate limits and use sandbox data. :::

OAuth2 Flow

import { OAuth2Client } from '@example/sdk'; const oauth = new OAuth2Client({ clientId: process.env.OAUTH_CLIENT_ID!, clientSecret: process.env.OAUTH_CLIENT_SECRET!, redirectUri: 'https://yourapp.com/callback', }); // Step 1: Generate authorization URL const authUrl = oauth.getAuthorizationUrl({ scope: ['read:users', 'write:users'], state: 'random_state_string', }); // Redirect user to authUrl... // Step 2: Handle callback const tokens = await oauth.exchangeCode(code); console.log('Access Token:', tokens.accessToken); console.log('Expires In:', tokens.expiresIn);

:::info OAuth2 tokens expire after 1 hour. Use refresh tokens to get new access tokens. :::

Refresh Tokens

// Refresh an expired token const newTokens = await oauth.refreshToken(refreshToken); // Store the new tokens await saveTokens({ accessToken: newTokens.accessToken, refreshToken: newTokens.refreshToken, expiresAt: Date.now() + newTokens.expiresIn * 1000, });

JWT Authentication

import { createClient, JWTAuth } from '@example/sdk'; const auth = new JWTAuth({ secret: process.env.JWT_SECRET!, algorithm: 'HS256', }); // Create a client with JWT auth const client = createClient({ auth: auth, }); // Generate a token for a user const token = auth.sign({ sub: 'user_123', role: 'admin', exp: Math.floor(Date.now() / 1000) + 3600, });

:::danger Keep your JWT secret secure. If compromised, rotate it immediately and invalidate all existing tokens. :::

Security Best Practices

  1. Rotate keys regularly - Generate new keys every 90 days
  2. Use environment variables - Never hardcode credentials
  3. Implement key scoping - Use the minimum required permissions
  4. Monitor usage - Set up alerts for unusual activity
// Example: Scoped API key const client = createClient({ apiKey: process.env.EXAMPLE_API_KEY!, // This key only has read access scope: ['read:users', 'read:data'], });

:::note Contact support to request custom scopes for your API keys. :::