react-native-auth-client
Version:
A comprehensive React Native authentication client with cross-platform support for iOS and Android. Features TurboModule architecture, username/password and Google SSO authentication, HTTP operations, file uploads/downloads with progress tracking, automat
407 lines (306 loc) • 11.3 kB
Markdown
with cross-platform support for iOS and Android. Features modern Swift async/await and Kotlin coroutines implementations with TurboModule support.
- ✅ **Cross-platform support** (iOS Swift + Android Kotlin)
- ✅ **TurboModule architecture** for both old and new React Native
- ✅ **Username/password authentication** with encryption support
- ✅ **Google SSO authentication** with ID token validation
- ✅ **HTTP operations** (GET, POST) with automatic token management
- ✅ **File operations** with progress tracking (upload/download)
- ✅ **Token management** with automatic refresh
- ✅ **Secure storage** (iOS Keychain / Android EncryptedSharedPreferences)
- ✅ **TypeScript support** with full type definitions
- ✅ **Progress tracking** for all operations
- ✅ **Request cancellation** support
- ✅ **PBKDF2 encryption** for request/response encryption
- ✅ **Singleton pattern** for iOS custom native modules access
## Installation
```bash
npm install react-native-auth-client
# or
yarn add react-native-auth-client
```
### iOS Setup
```bash
cd ios
bundle install # First time only
bundle exec pod install # Required after installation
```
### Android Setup
The library includes all required dependencies and will be automatically linked via React Native's autolinking.
## Usage
### Basic Setup
```typescript
import AuthClient, {
type AuthClientConfig,
type AuthResponse
} from 'react-native-auth-client';
// Initialize the client
const config: AuthClientConfig = {
baseUrl: 'https://your-api.com/',
isEncryptionRequired: false, // Set to true for encrypted requests
clientId: 'your-client-id',
passPhrase: 'encryption-passphrase',
};
const clientInfo = await AuthClient.initialize(config);
console.log('Client initialized:', clientInfo);
```
```typescript
import { type AuthCredentials } from 'react-native-auth-client';
const credentials: AuthCredentials = {
username: 'user@example.com',
password: 'password123',
};
try {
const result: AuthResponse = await AuthClient.authenticate(
'/api/authenticate',
credentials
);
if (result.loginStatus === 0) {
console.log('Authentication successful!');
}
} catch (error) {
console.error('Authentication failed:', error);
}
```
```typescript
const result = await AuthClient.googleAuthenticate(
'/api/auth/google',
'user@example.com',
'google-id-token-jwt'
);
```
```typescript
const response = await AuthClient.get('api/user/profile', {
headers: { 'Content-Type': 'application/json' }
});
```
```typescript
const data = { name: 'John', email: 'john@example.com' };
const response = await AuthClient.post('api/users', data, {
headers: { 'Content-Type': 'application/json' }
});
```
```typescript
import { type DeepFileUploadRequest, type ProgressEvent } from 'react-native-auth-client';
const fileRequest: DeepFileUploadRequest = {
file: {
fileContent: '/path/to/file.pdf', // File path without 'file://' prefix
},
node: {
parentNodeId: 'parent-folder-id',
hierarchyType: 'deep:file',
nodeTypeQname: 'deep:file',
name: 'document.pdf',
},
};
const result = await AuthClient.uploadFile(
'api/upload',
fileRequest,
(progress: ProgressEvent) => {
console.log(`Upload progress: ${Math.round(progress.progress * 100)}%`);
}
);
```
```typescript
const result = await AuthClient.downloadFile(
'api/files/download/123',
'/path/to/save/file.pdf',
{},
(progress: ProgressEvent) => {
console.log(`Download progress: ${Math.round(progress.progress * 100)}%`);
}
);
```
```typescript
const result = await AuthClient.downloadFileAsBase64(
'api/files/123',
{ headers: { 'Accept': 'image/jpeg' } }
);
console.log('Base64 data:', result.data);
```
```typescript
const requestBody = {
parameters: ["REDACT", "STAMP", "SIGNATURE"]
};
const result = await AuthClient.downloadFileWithPost(
'api/generate-document',
requestBody,
{ headers: { 'Content-Type': 'application/json' } }
);
```
```typescript
// Logout
await AuthClient.logout('api/logout');
// Get current client info
const info = await AuthClient.getClientInfo();
```
```typescript
// Cancel specific request (use the requestId from progress events)
AuthClient.cancelRequest('request-id');
// Cancel all active requests
AuthClient.cancelAllRequests();
```
```typescript
// Add global progress listeners
const uploadListener = AuthClient.addProgressListener('upload', (progress) => {
console.log(`Global upload progress: ${progress.progress * 100}%`);
});
const downloadListener = AuthClient.addProgressListener('download', (progress) => {
console.log(`Global download progress: ${progress.progress * 100}%`);
});
// Remove listeners when done
uploadListener.remove();
downloadListener.remove();
```
The library includes comprehensive TypeScript definitions:
```typescript
import AuthClient, {
type AuthClientConfig,
type AuthCredentials,
type GoogleAuthCredentials,
type AuthResponse,
type ClientInitResponse,
type HttpResponse,
type FileResponse,
type ProgressEvent,
type RequestConfig,
type FileUploadRequest,
type DeepFileUploadRequest,
} from 'react-native-auth-client';
```
Initialize the AuthClient with configuration.
Get current client initialization information.
Authenticate with username and password.
Authenticate with Google OAuth.
Execute HTTP GET request.
Execute HTTP POST request.
Upload a file with progress tracking.
Download a file to device storage.
Download a file as Base64 string.
Download a file using POST method.
Logout and clear session.
Cancel a specific request.
Cancel all active requests.
- **iOS**: Swift with async/await concurrency, URLSession networking
- **Android**: Kotlin with Coroutines, Retrofit + OkHttp networking
- **JavaScript**: TypeScript with comprehensive type definitions
The library provides singleton access for custom iOS native modules to use authenticated services directly:
```swift
import Foundation
@objc(CustomModuleExample)
public class CustomModuleExample: NSObject {
@objc
public func makeAuthenticatedRequest(_ endpoint: String,
completion: @escaping (String?, NSError?) -> Void) {
Task { @MainActor in
// Check if AuthClient is initialized
guard AuthClientManager.isInitialized() else {
let error = NSError(domain: "CustomModuleError", code: 1001,
userInfo: [NSLocalizedDescriptionKey: "AuthClient not initialized"])
completion(nil, error)
return
}
// Get authenticated network service
guard let networkService = AuthClientManager.getNetworkService() else {
let error = NSError(domain: "CustomModuleError", code: 1002,
userInfo: [NSLocalizedDescriptionKey: "NetworkService not available"])
completion(nil, error)
return
}
do {
// Make authenticated request (tokens handled automatically)
let data = try await networkService.requestData(
endpoint: endpoint,
method: "GET"
)
let response = String(data: data, encoding: .utf8) ?? "No data"
completion(response, nil)
} catch {
completion(nil, error as NSError)
}
}
}
@objc
public func checkAuthenticationStatus(completion: @escaping (Bool) -> Void) {
AuthClientManager.isAuthenticated(completion: completion)
}
}
```
**Key Benefits:**
- **Zero token management** required in custom modules
- **Automatic token refresh** on 401 errors
- **Thread-safe** MainActor-isolated access
- **Matches Android implementation** pattern
The library supports both React Native architectures:
- **Old Architecture**: Standard RCTEventEmitter with promise-based methods
- **New Architecture**: Full TurboModule protocol conformance
- **Token Storage**: iOS Keychain / Android EncryptedSharedPreferences
- **Automatic Token Refresh**: Handles 401 errors with fresh tokens
- **PBKDF2 Encryption**: Optional request/response encryption
- **Secure Logout**: Transmits current tokens to server for invalidation
The library includes a comprehensive example app demonstrating all features. To run it:
```bash
cd example
npm install
cd ios && bundle exec pod install && cd ..
npx react-native run-ios
npx react-native run-android
```
- [Development workflow](CONTRIBUTING.md
- [Sending a pull request](CONTRIBUTING.md
- [Code of conduct](CODE_OF_CONDUCT.md)
MIT
- Added iOS singleton pattern support for custom native modules
- Exposed AuthClientManager with public access to NetworkService, TokenManager, and Client
- Enhanced iOS architecture to match Android implementation pattern
- Custom modules can now access authenticated services without token management complexity
- Initial release with full cross-platform AuthClient implementation
- Complete TurboModule support for iOS and Android
- Comprehensive authentication, HTTP, and file operation features
- TypeScript definitions and example app included
---
Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
A comprehensive React Native authentication client