tenneo-auth-plugin
v0.1.5
Published
Production-ready ReactJS authentication plugin with OAuth PKCE support
Maintainers
Readme
tenneo-auth-plugin
Production-ready React authentication plugin with OAuth 2.0 PKCE support for enterprise applications.
Overview
tenneo-auth-plugin is a comprehensive authentication solution designed for modern React applications. It implements the OAuth 2.0 Authorization Code flow with PKCE (Proof Key for Code Exchange), providing secure authentication without exposing client secrets in browser-based applications.
The plugin features a robust multi-tenant architecture that automatically resolves tenant configuration based on tenant codes. This makes it ideal for SaaS platforms and enterprise applications where multiple tenants share the same codebase but require isolated authentication contexts.
Built with TypeScript and following clean architecture principles, the plugin handles the complete token lifecycle including automatic refresh, secure storage, and session management. The React Context API integration provides a seamless developer experience with hooks-based access to authentication state and methods.
Installation
npm install tenneo-auth-pluginRequirements
- React 18 or higher
- React DOM 18 or higher
- React Router (recommended for callback handling)
Quick Start
1. Wrap your application with AuthProvider
import { AuthProvider } from 'tenneo-auth-plugin';
function App() {
return (
<AuthProvider tenantCode="your-tenant-code">
<YourApplication />
</AuthProvider>
);
}2. Access authentication state with useAuth
import { useAuth } from 'tenneo-auth-plugin';
function Dashboard() {
const { isAuthenticated, isLoading, accessToken, logout } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return <div>Please log in to continue.</div>;
}
return (
<div>
<h1>Welcome to Dashboard</h1>
<button onClick={logout}>Sign Out</button>
</div>
);
}3. Handle OAuth callback
import { AuthCallback } from 'tenneo-auth-plugin';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<AuthProvider tenantCode="your-tenant-code">
<BrowserRouter>
<Routes>
<Route
path="/callback"
element={
<AuthCallback
successPath="/dashboard"
loginPath="/login"
/>
}
/>
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</BrowserRouter>
</AuthProvider>
);
}4. Protect routes
import { ProtectedRoute } from 'tenneo-auth-plugin';
function App() {
return (
<AuthProvider tenantCode="your-tenant-code">
<BrowserRouter>
<Routes>
<Route path="/callback" element={<AuthCallback />} />
<Route
path="/dashboard"
element={
<ProtectedRoute fallback={<div>Authenticating...</div>}>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
</BrowserRouter>
</AuthProvider>
);
}Features
- OAuth 2.0 PKCE flow for secure browser-based authentication
- Automatic token refresh before expiration
- Multi-tenant support with automatic tenant resolution
- Pluggable storage adapters (session, cookie, memory)
- Authentication event system for observability
- Strict TypeScript definitions throughout
- Runtime configuration override support
- Window-based configuration injection
- Clean layered architecture
- Tree-shakeable ESM and CJS builds
- React 18+ compatibility
AuthProvider Props
| Prop | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| tenantCode | string | No | - | Tenant code for configuration resolution |
| appId | string | No | '' | Application identifier for storage namespacing |
| autoInit | boolean | No | true | Automatically initialize authentication on mount |
| storageAdapter | StorageAdapter | No | null | Custom storage adapter instance |
Hooks API
useAuth()
Primary hook for accessing authentication state and methods.
import { useAuth } from 'tenneo-auth-plugin';
function Component() {
const {
isAuthenticated, // boolean - Current authentication status
accessToken, // string | null - Current access token
isLoading, // boolean - Loading state during auth operations
error, // string | null - Error message if any
login, // () => Promise<void> - Trigger login flow
logout, // () => Promise<void> - Sign out and clear session
refreshToken, // () => Promise<string> - Manually refresh token
getAccessToken, // () => Promise<string> - Get valid token (auto-refresh)
} = useAuth();
}useAuthInit()
Hook for manual authentication initialization.
import { useAuthInit } from 'tenneo-auth-plugin';
function Component() {
const {
isLoading, // boolean - Initialization in progress
error, // string | null - Initialization error
init, // () => Promise<void> - Trigger initialization
} = useAuthInit();
useEffect(() => {
init();
}, [init]);
}Components
AuthCallback
Handles OAuth authorization callback and token exchange.
import { AuthCallback } from 'tenneo-auth-plugin';
<AuthCallback
loginPath="/login" // Redirect on error (default: '/login')
successPath="/dashboard" // Redirect on success (default: '/dashboard')
homePath="/" // Fallback path (default: '/')
/>ProtectedRoute
Wrapper component that ensures authentication before rendering children.
import { ProtectedRoute } from 'tenneo-auth-plugin';
<ProtectedRoute
fallback={<LoadingSpinner />} // Shown while checking auth
autoLogin={true} // Auto-redirect to login (default: true)
>
<ProtectedContent />
</ProtectedRoute>Core API
bootstrap()
Initializes the authentication flow. Called automatically by AuthProvider when autoInit is true.
import { bootstrap } from 'tenneo-auth-plugin';
await bootstrap();getAccessToken()
Retrieves a valid access token, automatically refreshing if expired.
import { getAccessToken } from 'tenneo-auth-plugin';
const token = await getAccessToken();logout()
Signs out the user and clears all authentication data.
import { logout } from 'tenneo-auth-plugin';
await logout();createAuthEngine()
Creates an authentication engine instance for advanced use cases.
import { createAuthEngine } from 'tenneo-auth-plugin';
const engine = createAuthEngine(runtime);
// Subscribe to state changes
const unsubscribe = engine.subscribe((state) => {
console.log('Status:', state.status);
console.log('Token:', state.accessToken);
});
// Initialize
await engine.init();
// Operations
await engine.login();
await engine.logout();
const token = await engine.getAccessToken();Configuration
Environment Variables
Configure the plugin using environment variables. For Vite applications, use the VITE_ prefix.
# OAuth Server URL
VITE_AUTH_SERVER_URL=https://auth.example.com
# API Base URLs
VITE_API_TENANT_RESOLUTION_BASE_URL=https://api.example.com/api/v1
VITE_API_AUTH_BASE_URL=https://auth.example.com
# Default Configuration
VITE_CLIENT_ID=your-client-id
VITE_TENANT_ID=your-tenant-id
VITE_CLIENTCODE=your-tenant-codeWindow Runtime Configuration
Inject configuration at runtime without rebuilding the application.
<script>
window.__AUTH_CONFIG__ = {
clientId: 'runtime-client-id',
tenantId: 'runtime-tenant-id',
basePath: '/app',
};
</script>Configuration Priority
Configuration is resolved in the following order (highest priority first):
- Props passed to AuthProvider
- Window configuration (
window.__AUTH_CONFIG__) - Environment variables
- Built-in defaults
Programmatic Configuration
import { setConfig, Config } from 'tenneo-auth-plugin';
// Override configuration
setConfig({
clientId: 'custom-client-id',
tenantId: 'custom-tenant-id',
basePath: '/my-app',
});
// Access resolved configuration
const authServerUrl = Config.getAuthServerUrl();
const clientId = Config.getClientId();
const allConfig = Config.getAll();Security
PKCE Protection
The plugin implements PKCE (Proof Key for Code Exchange) to prevent authorization code interception attacks. A cryptographically random code verifier is generated for each authentication request and never transmitted to the authorization server.
CSRF Protection
OAuth state parameter validation prevents cross-site request forgery attacks. Each authentication request includes a unique state value that is verified during the callback.
Token Isolation
Authentication tokens are stored with tenant-specific namespacing, ensuring complete isolation between different tenants in multi-tenant deployments.
HTTPS Enforcement
Production environments automatically enforce HTTPS for all authentication-related requests and redirects.
Session Security
Tokens are stored in sessionStorage by default, ensuring they are cleared when the browser tab is closed. For enhanced security requirements, custom storage adapters can be configured.
Storage Adapters
import {
createSecureSessionStorageAdapter,
createCookieStorageAdapter,
createMemoryStorageAdapter,
} from 'tenneo-auth-plugin';
// Session storage (default, cleared on tab close)
const sessionAdapter = createSecureSessionStorageAdapter({
tenantId: 'tenant-123',
appId: 'my-app'
});
// Cookie storage (persistent)
const cookieAdapter = createCookieStorageAdapter({
tenantId: 'tenant-123',
appId: 'my-app'
});
// Memory storage (testing)
const memoryAdapter = createMemoryStorageAdapter({
tenantId: 'tenant-123',
appId: 'my-app'
});
// Use custom adapter
<AuthProvider tenantCode="abc" storageAdapter={sessionAdapter}>
<App />
</AuthProvider>Events
Subscribe to authentication events for logging, analytics, or custom behavior.
import { subscribeAuthEvent, AuthEventNames } from 'tenneo-auth-plugin';
// Subscribe to login events
const unsubscribe = subscribeAuthEvent(AuthEventNames.LOGIN, (payload) => {
console.log('User authenticated');
});
// Available events
AuthEventNames.LOGIN // User successfully authenticated
AuthEventNames.LOGOUT // User signed out
AuthEventNames.REFRESH // Token refreshed
AuthEventNames.ERROR // Authentication error occurredTypeScript Support
All types are exported for use in TypeScript applications.
import type {
TenantConfig,
TokenResponse,
AuthState,
AuthContextValue,
EnvConfig,
AuthTokens,
StorageAdapter,
AuthEngine,
AuthEngineState,
SDKConfig,
RuntimeConfigOverrides,
} from 'tenneo-auth-plugin';Versioning
This package follows Semantic Versioning (SemVer):
- Major versions contain breaking changes
- Minor versions add backward-compatible features
- Patch versions include backward-compatible bug fixes
- Beta versions are pre-release versions for testing
License
MIT
