@bernierllc/contentful-auth
v1.0.8
Published
OAuth 2.0 authentication and token management for Contentful
Readme
@bernierllc/contentful-auth
OAuth 2.0 authentication and token management for Contentful.
Features
- OAuth 2.0 authorization URL generation
- Authorization code exchange for access tokens
- Automatic token refresh with refresh tokens
- Token validation and expiration checking
- Secure credential storage interfaces
- Multi-organization and space-level token management
Installation
npm install @bernierllc/contentful-authUsage
Basic Authentication Flow
import { ContentfulAuth, TokenStorage } from '@bernierllc/contentful-auth';
// Create auth instance
const auth = new ContentfulAuth({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://your-app.com/callback'
});
// Step 1: Generate authorization URL
const authUrl = auth.getAuthorizationUrl('state-value', 'content_management_manage');
// Redirect user to authUrl
// Step 2: Exchange authorization code for tokens
const tokens = await auth.exchangeCodeForTokens(code);
console.log('Access token:', tokens.access_token);
console.log('Refresh token:', tokens.refresh_token);Token Refresh
// Manually refresh token
const newTokens = await auth.refreshAccessToken(refreshToken);
// Or use automatic refresh with storage
const storage: TokenStorage = {
async store(key, tokens) {
// Store tokens in your database
await db.saveTokens(key, tokens);
},
async retrieve(key) {
// Retrieve tokens from your database
return await db.getTokens(key);
},
async delete(key) {
// Delete tokens from your database
await db.deleteTokens(key);
}
};
const authWithStorage = new ContentfulAuth(config, storage);
// Automatically refreshes if token is expired
const validToken = await authWithStorage.getValidToken('org-123');Token Validation
const isValid = await auth.validateToken(accessToken);
if (!isValid) {
console.log('Token is invalid or expired');
}API
ContentfulAuth
Constructor
constructor(config: ContentfulAuthConfig, storage?: TokenStorage)config.clientId- OAuth client IDconfig.clientSecret- OAuth client secretconfig.redirectUri- OAuth redirect URIconfig.tokenUrl- (Optional) Custom token URLconfig.authorizationUrl- (Optional) Custom authorization URLconfig.logger- (Optional) Custom logger instancestorage- (Optional) Token storage implementation
Methods
getAuthorizationUrl(state?: string, scope?: string): string
Generate OAuth authorization URL.
exchangeCodeForTokens(code: string): Promise<ContentfulOAuthTokens>
Exchange authorization code for access and refresh tokens.
refreshAccessToken(refreshToken: string): Promise<ContentfulOAuthTokens>
Refresh access token using refresh token.
validateToken(accessToken: string): Promise<boolean>
Validate access token against Contentful API.
getValidToken(storageKey: string): Promise<string>
Get a valid access token, automatically refreshing if expired (requires storage).
storeTokens(key: string, tokens: ContentfulOAuthTokens): Promise<void>
Store tokens (requires storage).
revokeTokens(storageKey: string): Promise<void>
Revoke and delete tokens (requires storage).
TokenStorage Interface
interface TokenStorage {
store(key: string, tokens: ContentfulOAuthTokens): Promise<void>;
retrieve(key: string): Promise<ContentfulOAuthTokens | null>;
delete(key: string): Promise<void>;
}Implement this interface to provide persistent token storage.
Token Expiration
Tokens are automatically refreshed when:
- Less than 5 minutes remaining before expiration
getValidToken()is called with valid refresh token
Error Handling
try {
const tokens = await auth.exchangeCodeForTokens(code);
} catch (error) {
console.error('OAuth failed:', error.message);
}All methods throw descriptive errors on failure.
Integration
Logger Integration
This package uses @bernierllc/logger for structured logging. The logger is optional and will use a no-op logger if not provided. To enable logging:
import { ContentfulAuth } from '@bernierllc/contentful-auth';
import { Logger } from '@bernierllc/logger';
const logger = new Logger({ level: 'info' });
const auth = new ContentfulAuth({
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
redirectUri: 'https://your-app.com/callback',
logger
});NeverHub Integration
This package supports optional NeverHub integration for event tracking and monitoring. NeverHub integration is detected automatically and provides graceful degradation if NeverHub is not available.
When NeverHub is available, authentication events (token exchanges, refreshes, validation) are automatically tracked:
import { ContentfulAuth } from '@bernierllc/contentful-auth';
import { NeverHubAdapter } from '@bernierllc/neverhub-adapter';
// NeverHub will be auto-detected if available
const auth = new ContentfulAuth(config);
// Authentication events are automatically logged to NeverHub
await auth.exchangeCodeForTokens(code); // Event tracked in NeverHubIf NeverHub is not available, the package operates normally without event tracking. This ensures the package works in all environments with graceful degradation.
License
Copyright (c) 2025 Bernier LLC. See LICENSE file for details.
