identity-react
v1.1.4
Published
Reclaim Identity React Client
Downloads
279
Readme
Reclaim Identity for React
Reclaim Identity is a React-based authentication module that provides an easy-to-use interface for authenticating users with the Reclaim Protocol. It manages the OAuth 2.0 flow, handling user sign-in, token management, and user data retrieval within your React application.
Features
- React-friendly authentication flow
- OAuth 2.0 authentication with popup window
- Automatic token management
- User data retrieval and caching
- Event-based auth state changes
- TypeScript support
- CSRF protection with state validation
- Session-based authentication
Installation
You can install the Reclaim Identity package using npm:
npm i identity-react
Or using yarn:
yarn add identity-react
Usage
Initializing ReclaimAuth
In your React application, typically in a context provider or a top-level component:
import getReclaimAuth from 'identity-react';
const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
const auth = getReclaimAuth(clientId, clientSecret, redirectUri);
function App() {
// Your app code
}
Using ReclaimAuth in a Component
import React, { useState, useEffect } from 'react';
import getReclaimAuth, { type ReclaimUser } from 'identity-react';
const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
function AuthComponent() {
const [user, setUser] = useState<ReclaimUser | null>(null);
const auth = getReclaimAuth(clientId, clientSecret, redirectUri);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((newUser) => {
setUser(newUser);
});
return () => unsubscribe();
}, []);
const handleSignIn = async () => {
try {
const user = await auth.signIn();
console.log('Signed in user:', user);
} catch (error) {
console.error('Sign in failed:', error);
}
};
const handleSignOut = async () => {
try {
await auth.signOut();
} catch (error) {
console.error('Sign out failed:', error);
}
};
return (
<div>
{user ? (
<>
<p>Welcome, {user.id}</p>
<button onClick={handleSignOut}>Sign Out</button>
</>
) : (
<button onClick={handleSignIn}>Sign In</button>
)}
</div>
);
}
Creating a Custom Hook
You can create a custom hook to simplify the use of ReclaimAuth across your React components:
import { useState, useEffect } from 'react';
import getReclaimAuth, { type ReclaimUser } from 'identity-react';
const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
export function useReclaimAuth() {
const [user, setUser] = useState<ReclaimUser | null>(null);
const auth = getReclaimAuth(clientId, clientSecret, redirectUri);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(setUser);
return () => unsubscribe();
}, []);
return {
user,
signIn: () => auth.signIn(),
signOut: () => auth.signOut(),
getCurrentUser: () => auth.getCurrentUser(),
};
}
API Reference
getReclaimAuth(clientId: string, clientSecret: string, redirectUri: string): ReclaimAuth
Returns the singleton instance of ReclaimAuth. Both parameters are required on first initialization.
signIn(): Promise<ReclaimUser>
Initiates the sign-in process by opening a popup window for authentication. Returns a Promise that resolves with the user data once the authentication flow is complete.
getCurrentUser(): ReclaimUser | null
Returns the current authenticated user object, or null if no user is signed in.
onAuthStateChanged(callback: (user: ReclaimUser | null) => void): () => void
Sets up a listener for changes in authentication state. Returns an unsubscribe function to remove the listener.
signOut(): Promise<void>
Signs out the current user and clears all authentication data.
Types
ReclaimUser
interface ReclaimUser {
id: string;
userData: { [key: string]: string };
additionalData: { [key: string]: string }[];
}
Configuration
The ReclaimAuth module requires the following configuration:
clientId
: Your Reclaim Protocol application ID (required)clientSecret
: Your Reclaim Protocol application secret (required)redirectUri
: The URI where your application will handle the OAuth callback (required)apiBaseUrl
: Defaults to 'https://identity.reclaimprotocol.org'env
: Defaults to 'production'
Security Features
- CSRF protection using state parameter validation
- Secure cookie handling with httpOnly flag
- Origin validation for popup message handling
- Credentials included in API requests
- Secure popup window management
Browser Requirements
- Modern browsers with support for:
- Promises
- Fetch API
- Web Crypto API
- PostMessage API
- Cookies
- ES6+ features
Error Handling
The SDK includes comprehensive error handling for:
- Popup blocking
- Authentication failures
- Network errors
- CSRF attempts
- Token exchange failures
- User data fetch failures
Example error handling:
try {
await auth.signIn();
} catch (error) {
if (error.message.includes('popup')) {
// Handle popup blocked
} else if (error.message.includes('code')) {
// Handle authorization code error
} else if (error.message.includes('token')) {
// Handle token exchange error
} else {
// Handle other errors
}
}
Best Practices
- Always clean up auth state listeners using the unsubscribe function
- Handle authentication errors appropriately
- Use HTTPS in production
- Store sensitive configuration in environment variables
- Implement proper error boundaries in your React components
Troubleshooting
Common issues and solutions:
Popup Blocked
- Ensure signIn() is called in response to a user action
- Check browser popup settings
Authentication Failures
- Verify clientId and redirectUri are correct
- Check API endpoint accessibility
- Validate cookie settings
Session Issues
- Clear browser cookies
- Check for proper credential inclusion
- Verify CORS settings
Integration Issues
- Ensure proper initialization
- Check for proper event handling
- Verify proper TypeScript types usage
For additional support, please refer to the Reclaim Protocol documentation or reach out to the support team.