@autolabz/oauth-app-sdk
v1.0.0
Published
AutoLab OAuth App SDK - client_credentials flow for backend applications
Maintainers
Readme
@autolabz/oauth-app-sdk
OAuth2 client_credentials flow SDK for backend applications.
This SDK enables your backend services to authenticate with AutoLab using the OAuth2 client_credentials grant type, allowing them to access protected APIs on behalf of themselves (not a user).
Features
- ✅ OAuth2 client_credentials flow implementation
- ✅ Automatic token caching and refresh
- ✅ AuthBridge adapter for seamless integration with other AutoLab SDKs
- ✅ TypeScript support with full type definitions
- ✅ Lightweight and zero dependencies (except axios)
Installation
npm install @autolabz/oauth-app-sdkUsage
Basic Usage
import { OAuthAppClient } from '@autolabz/oauth-app-sdk';
// Create an OAuth app client
const appClient = new OAuthAppClient({
clientId: 'your-client-id',
clientSecret: 'cs_live_...', // Get this when creating the OAuth2 app
authServiceUrl: 'https://your-auth-service.com/api'
});
// Get an access token (automatically cached and refreshed)
const accessToken = await appClient.getAccessToken();
// Use the token in your API requests
const response = await fetch('https://your-api.com/resource', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});Integration with Other AutoLab SDKs
The SDK provides an AuthBridge adapter that works seamlessly with other AutoLab SDKs:
import { OAuthAppClient, createAuthBridge } from '@autolabz/oauth-app-sdk';
import { createPointsClient } from '@autolabz/points-sdk';
import { createDataClient } from '@autolabz/data-sdk';
// 1. Create the OAuth app client
const appClient = new OAuthAppClient({
clientId: 'your-client-id',
clientSecret: 'cs_live_...',
authServiceUrl: 'https://your-auth-service.com/api'
});
// 2. Create an AuthBridge
const authBridge = createAuthBridge(appClient, {
onUnauthorized: () => {
console.error('Authentication failed! Check your credentials.');
}
});
// 3. Use the bridge with other SDKs
const pointsClient = createPointsClient({
baseURL: 'https://your-points-service.com',
auth: authBridge
});
const dataClient = createDataClient({
baseURL: 'https://your-data-service.com',
auth: authBridge
});
// 4. Make API calls (authentication is handled automatically)
const balance = await pointsClient.getMyBalance();
const data = await dataClient.query({ table: 'users' });API Reference
OAuthAppClient
Main client class for OAuth2 client_credentials flow.
Constructor
new OAuthAppClient(config: OAuthAppClientConfig)Parameters:
config.clientId(string, required): Your OAuth2 application's client IDconfig.clientSecret(string, required): Your OAuth2 application's client secretconfig.authServiceUrl(string, required): Base URL of the auth service (e.g.,https://your-domain.com/api)
Methods
getAccessToken(): Promise<string | null>
Get an access token. Automatically caches and refreshes tokens as needed.
Returns the cached token if it's still valid (with 10% buffer), otherwise fetches a new one.
fetchNewToken(): Promise<string>
Explicitly fetch a new access token from the auth service.
getClientId(): string
Get the client ID.
clearCache(): void
Clear the cached token. Useful for testing or forcing a refresh.
createAuthBridge
Create an AuthBridge adapter for use with other AutoLab SDKs.
createAuthBridge(
client: OAuthAppClient,
options?: CreateAuthBridgeOptions
): AuthBridgeParameters:
client(OAuthAppClient, required): An instance of OAuthAppClientoptions.onUnauthorized(function, optional): Callback function called when authentication fails
Returns: AuthBridge object compatible with other AutoLab SDKs
How It Works
Token Request: When you call
getAccessToken(), the SDK sends a POST request to/oauth/tokenwithgrant_type=client_credentials.Token Caching: The SDK caches the access token and its expiration time.
Automatic Refresh: Before the token expires (with a 10% buffer), the SDK automatically fetches a new token.
AuthBridge: The bridge adapter wraps the client to provide a consistent interface for other AutoLab SDKs.
Requirements
- An OAuth2 application created in AutoLab with
authMode: 'OAUTH2' - Node.js 14 or higher
- TypeScript 4.5+ (if using TypeScript)
Getting Your Credentials
- Log in to the AutoLab Admin Portal
- Navigate to OAuth Applications
- Create a new application with OAuth2 mode
- Copy the
clientIdandclientSecret(the secret is only shown once!) - Configure your allowed scopes and redirect URIs
Security Best Practices
⚠️ Important: Your clientSecret is sensitive and should be kept secure!
- ❌ Never commit your client secret to version control
- ❌ Never expose your client secret in client-side code
- ✅ Store credentials in environment variables or a secure vault
- ✅ Use different credentials for development and production
- ✅ Rotate your client secret regularly
Environment Variables
We recommend storing your credentials as environment variables:
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=cs_live_...
AUTH_SERVICE_URL=https://your-auth-service.com/apiThen in your code:
const appClient = new OAuthAppClient({
clientId: process.env.OAUTH_CLIENT_ID!,
clientSecret: process.env.OAUTH_CLIENT_SECRET!,
authServiceUrl: process.env.AUTH_SERVICE_URL!
});License
MIT
Support
For issues and questions, please contact the AutoLab team or open an issue in the repository.
