@cloudwick/cams-auth-client
v0.1.2
Published
CAMS authentication client library for React applications with Context API and localStorage persistence
Downloads
515
Readme
@cloudwick/cams-auth-client
React authentication library for CAMS (Central Authentication Management System)
What This Package Does
@cloudwick/cams-auth-client provides OAuth 2.0 authentication for React apps with CAMS:
- ✅ OAuth 2.0 - Authorization code flow with automatic callback handling
- ✅ Session Management - Auto-validation, token renewal, persistence
- ✅ Cross-Tab Sync - Login/logout synced across browser tabs
- ✅ SSO Support - Cross-domain single sign-on via authBridge
- ✅ React Hooks - Clean API (
useCamsAuth,useSessionValidator,usePatApi) - ✅ TypeScript - Full type safety included
- ✅ Zero Config - No manual OAuth routes needed
Installation
npm install @cloudwick/cams-auth-client
# or
yarn add @cloudwick/cams-auth-clientRequirements:
- React >= 16.8.0
- ⚠️ Your application must be onboarded in CAMS - Ensure your
appIdis registered in CAMS admin portal before integration (applies to all environments: local, staging, production)
Quick Example
import { CamsAuthProvider, AuthGuard, useCamsAuth } from "@cloudwick/cams-auth-client";
// 1. Wrap your app
<CamsAuthProvider
appId="your-app-id"
camsApiGateway="https://api.cams.example.com"
redirectUri={`${window.location.origin}/auth/callback`}
camsLoginUrl="https://cams.example.com"
>
<AuthGuard fallback={<LoginPage />}>
<Dashboard />
</AuthGuard>
</CamsAuthProvider>
// 2. Use the hook
function Dashboard() {
const { user, logout } = useCamsAuth();
return <button onClick={logout}>Logout {user?.userId}</button>;
}📖 Complete Documentation
For full integration guide, examples, and best practices:
- INTEGRATION_GUIDE.md - Step-by-step integration guide (5-minute quick start, common scenarios, troubleshooting)
- Confluence - Internal documentation
INTEGRATION_GUIDE.md includes:
- Quick start (working code in 5 minutes)
- Complete integration steps
- Common scenarios (redirect after login, Redux integration, etc.)
- Caching strategy & performance
- How it works (deep dive)
- Troubleshooting guide
- Best practices
API Reference
CamsAuthProvider Props
Required
| Prop | Type | Description |
|------|------|-------------|
| appId | string | Application ID registered in CAMS |
| camsApiGateway | string | CAMS API base URL |
| redirectUri | string | OAuth callback URL |
| camsLoginUrl | string | CAMS login page URL |
Optional
| Prop | Type | Default |
|------|------|---------|
| validationInterval | number | 600000 (10 min) |
| enableAutoValidation | boolean | true |
Lifecycle Callbacks
| Callback | Signature |
|----------|-----------|
| onLoginSuccess | (user: UserInfo, tokens: TokenSet) => void |
| onLoginError | (error: Error) => void |
| onSessionExpired | () => void |
| onTokenRenewed | (tokens: TokenSet) => void |
| onLogout | () => void |
| onStateHydrated | (state: AuthState) => void |
| onError | (error: Error, context: string) => void |
See INTEGRATION_GUIDE.md for callback usage examples
Hooks
useCamsAuth
const {
isAuthenticated: boolean;
isLoading: boolean;
user: UserInfo | null;
tokens: TokenSet | null;
startLogin: () => Promise<void>;
logout: () => Promise<void>;
forceTokenRenewal: () => Promise<{renewed: boolean, tokens: TokenSet | null}>;
} = useCamsAuth();useSessionValidator
const {
validateNow: () => Promise<boolean>;
lastValidatedAt: string | null;
isValidating: boolean;
} = useSessionValidator();usePatApi
const {
createToken: (params: CreatePatRequest) => Promise<CreateTokenResponse>;
listTokens: (params?: ListPatsRequest) => Promise<ListPatsResponse>;
invalidateCache: () => void;
} = usePatApi();See INTEGRATION_GUIDE.md for hook examples
Components
AuthGuard
<AuthGuard
fallback={<LoginPage />} // Required: shown when not authenticated
loader={<LoadingSpinner />} // Optional: shown while checking auth
>
<ProtectedContent />
</AuthGuard>TypeScript Types
Core Types
interface AuthState {
isSignUpSupported: boolean;
opaqueToken: string | null;
sessionActive: boolean;
validSession: boolean;
userId: string | null;
email: string | null;
lastValidatedAt: string | null;
isLoading: boolean;
authenticationState: CamsAuthState;
tokenExpiresAt: number | null;
}
type CamsAuthState =
| "Uninitialized"
| "SilentSsoChecking"
| "LoginRedirecting"
| "Authenticated"
| "Unauthenticated"
| "Renewing"
| "LogoutInProgress"
| "SessionExpired"
| "Error";
interface TokenSet {
opaqueToken: string;
tokenExpiresAt: number | null;
}
interface UserInfo {
userId: string | null;
email?: string | null;
}Configuration
interface CamsAuthConfig {
// Required
camsApiGateway: string;
appId: string;
redirectUri: string;
camsLoginUrl: string;
// Optional
validationInterval?: number;
enableAutoValidation?: boolean;
// Callbacks
onLoginSuccess?: (user: UserInfo, tokens: TokenSet) => void;
onLoginError?: (error: Error) => void;
onLogout?: () => void;
onTokenRenewed?: (tokens: TokenSet) => void;
onTokenRenewalError?: (error: Error) => void;
onSessionExpired?: () => void;
onSessionValidated?: (isValid: boolean, tokens: TokenSet) => void;
onStateHydrated?: (state: AuthState) => void;
onStateChange?: (state: AuthState, prevState: AuthState) => void;
onError?: (error: Error, context: string) => void;
onSignUpStart?: () => void;
onSignUpError?: (error: Error) => void;
}Package Exports
// Provider & Context
export { CamsAuthProvider };
export { CamsAuthContext, useCamsAuthContext };
// Hooks
export { useCamsAuth, useSessionValidator, usePatApi };
// Components
export { AuthGuard };
// Utils
export { urlBuilder, formatQueryParams, extractError, extractMessage };
// Constants
export { currentOrigin, unAuthenticatedCamsUri };
// Types
export type {
AuthState, TokenSet, UserInfo, CamsAuthState,
CamsAuthConfig, PrepareAuthResponse, CallbackResponse,
CreatePatRequest, ListPatsResponse
};Key Features
Automatic OAuth Handling
Provider detects ?code=...&state=... in URL and exchanges for tokens automatically. No manual callback route needed.
Cross-Tab Synchronization
Login/logout in one tab updates all tabs instantly via localStorage events.
Automatic Token Renewal
Tokens refreshed automatically on 401/403 API responses. Session expires gracefully with onSessionExpired callback.
Caching
- IdP Hint: 30 minutes (localStorage)
- PAT List: 15 minutes (in-memory)
- Session Validation: 2-minute cooldown across tabs
See INTEGRATION_GUIDE.md for caching details and performance optimization
Storage
Auth state persists in localStorage: {hostname}:cams_auth_state
CAMS API Endpoints
| Endpoint | Method | Purpose |
|----------|--------|---------|
| /auth/prepare | POST | Get OAuth URL |
| /auth/callback | GET | Exchange code for tokens |
| /auth/renew | POST | Refresh tokens |
| /auth/validate | GET | Check session |
| /auth/logout | DELETE | End session |
| /me/pats | POST/GET | Manage tokens |
Local Development Setup
Cookie Domain Considerations
Localhost doesn't support cross-domain cookies required for SSO. Use localtest.me domain for local development:
# Instead of localhost:3000
https://localtest.me:3000
# For subdomains (recommended for multi-app development)
https://myapp.localtest.me:3000
https://otherapp.localtest.me:3001Scenario 1: Developing Both CAMS and Your App Locally
When running both CAMS and your app on localhost:
// Configure provider with local CAMS endpoints
<CamsAuthProvider
appId="your-app-id"
camsApiGateway="https://localtest.me:8080" // Local CAMS API
redirectUri="https://myapp.localtest.me:3000/auth/callback"
camsLoginUrl="https://localtest.me:8080" // Local CAMS login
>Run apps on different ports:
- CAMS:
https://localtest.me:8080 - Your App:
https://myapp.localtest.me:3000
Scenario 2: Developing Only Your App (CAMS in Production)
Point to production CAMS endpoints:
<CamsAuthProvider
appId="your-app-id"
camsApiGateway="https://api.cams.production.com" // Production CAMS
redirectUri="https://myapp.localtest.me:3000/auth/callback"
camsLoginUrl="https://cams.production.com" // Production login
>See INTEGRATION_GUIDE.md for complete local development setup
Common Issues
"useCamsAuthContext must be used within CamsAuthProvider"
→ Hook used outside provider tree
Infinite redirect loop
→ redirectUri mismatch between provider and CAMS config
Session expires immediately
→ Invalid appId or app not registered
Cookies not working in local development
→ Use localtest.me domain instead of localhost (see Local Development Setup)
App not registered / 401 errors
→ Ensure app ID is onboarded in CAMS admin portal with correct callback URLs
See INTEGRATION_GUIDE.md for complete troubleshooting guide
Migration from AWS Amplify
| Amplify | CAMS Auth Client |
|---------|------------------|
| Amplify.configure() | <CamsAuthProvider> |
| Auth.signIn() | startLogin() |
| Auth.signOut() | logout() |
| Auth.currentUser() | useCamsAuth().user |
See INTEGRATION_GUIDE.md for complete migration guide
Support & Documentation
- INTEGRATION_GUIDE.md - Complete integration guide
- Confluence - Internal wiki
- Issues: Report via internal tracker
- Questions: Contact CAMS team @ Cloudwick
License
MIT © Cloudwick Technologies
Package: @cloudwick/cams-auth-client v0.1.1
Maintained by: CAMS Team @ Cloudwick
📖 For complete integration guide, see INTEGRATION_GUIDE.md
