SDK Setup Guide
Get started with the Authsec SDK to integrate authentication and authorization into your AI applications and MCP servers.
Installation
Authsec provides SDKs for multiple programming languages and platforms.
JavaScript/TypeScript (Node.js)
npm install @authsec/sdk
# or
yarn add @authsec/sdk
JavaScript/TypeScript (Browser)
npm install @authsec/web-sdk
# or
yarn add @authsec/web-sdk
Python
pip install authsec-sdk
Java
<!-- Maven -->
<dependency>
<groupId>com.authsec</groupId>
<artifactId>authsec-sdk</artifactId>
<version>1.0.0</version>
</dependency>
// Gradle
implementation 'com.authsec:authsec-sdk:1.0.0'
.NET
dotnet add package Authsec.SDK
Go
go get github.com/authsec/authsec-go
Basic Configuration
Environment Variables
Create a .env file in your project root:
# Required configuration
AUTHSEC_DOMAIN=your-domain.authsec.com
AUTHSEC_CLIENT_ID=your-client-id
AUTHSEC_CLIENT_SECRET=your-client-secret
# Optional configuration
AUTHSEC_AUDIENCE=https://api.yourapp.com
AUTHSEC_SCOPE=openid profile ai:access
AUTHSEC_REDIRECT_URI=http://localhost:3000/callback
SDK Initialization
JavaScript/TypeScript (Node.js)
import { AuthsecClient } from '@authsec/sdk';
import dotenv from 'dotenv';
dotenv.config();
const authsec = new AuthsecClient({
domain: process.env.AUTHSEC_DOMAIN,
clientId: process.env.AUTHSEC_CLIENT_ID,
clientSecret: process.env.AUTHSEC_CLIENT_SECRET,
audience: process.env.AUTHSEC_AUDIENCE,
scope: process.env.AUTHSEC_SCOPE
});
export default authsec;
JavaScript/TypeScript (Browser)
import { AuthsecWebClient } from '@authsec/web-sdk';
const authsec = new AuthsecWebClient({
domain: 'your-domain.authsec.com',
clientId: 'your-client-id',
redirectUri: window.location.origin + '/callback',
scope: 'openid profile ai:access'
});
Python
import os
from authsec import AuthsecClient
# Load from environment variables
authsec = AuthsecClient(
domain=os.getenv('AUTHSEC_DOMAIN'),
client_id=os.getenv('AUTHSEC_CLIENT_ID'),
client_secret=os.getenv('AUTHSEC_CLIENT_SECRET'),
audience=os.getenv('AUTHSEC_AUDIENCE'),
scope=os.getenv('AUTHSEC_SCOPE')
)
Java
import com.authsec.AuthsecClient;
import com.authsec.AuthsecConfig;
AuthsecConfig config = AuthsecConfig.builder()
.domain(System.getenv("AUTHSEC_DOMAIN"))
.clientId(System.getenv("AUTHSEC_CLIENT_ID"))
.clientSecret(System.getenv("AUTHSEC_CLIENT_SECRET"))
.audience(System.getenv("AUTHSEC_AUDIENCE"))
.build();
AuthsecClient authsec = new AuthsecClient(config);
.NET
using Authsec;
var config = new AuthsecConfig
{
Domain = Environment.GetEnvironmentVariable("AUTHSEC_DOMAIN"),
ClientId = Environment.GetEnvironmentVariable("AUTHSEC_CLIENT_ID"),
ClientSecret = Environment.GetEnvironmentVariable("AUTHSEC_CLIENT_SECRET"),
Audience = Environment.GetEnvironmentVariable("AUTHSEC_AUDIENCE")
};
var authsec = new AuthsecClient(config);
Go
package main
import (
"os"
"github.com/authsec/authsec-go"
)
func main() {
config := authsec.Config{
Domain: os.Getenv("AUTHSEC_DOMAIN"),
ClientID: os.Getenv("AUTHSEC_CLIENT_ID"),
ClientSecret: os.Getenv("AUTHSEC_CLIENT_SECRET"),
Audience: os.Getenv("AUTHSEC_AUDIENCE"),
}
client := authsec.NewClient(config)
}
Authentication Flows
1. Client Credentials Flow (Service-to-Service)
Best for AI agents and MCP servers that operate without user interaction.
// Node.js example
async function authenticateService() {
try {
const token = await authsec.getClientCredentialsToken({
audience: 'https://api.yourapp.com',
scope: 'ai:generate ai:analyze mcp:tools'
});
console.log('Service authenticated successfully');
return token.access_token;
} catch (error) {
console.error('Service authentication failed:', error.message);
throw error;
}
}
# Python example
async def authenticate_service():
try:
token = await authsec.get_client_credentials_token(
audience='https://api.yourapp.com',
scope='ai:generate ai:analyze mcp:tools'
)
print('Service authenticated successfully')
return token['access_token']
except Exception as error:
print(f'Service authentication failed: {error}')
raise
2. Authorization Code Flow (Web Applications)
For web applications that need user authentication.
// Redirect user to login
function redirectToLogin() {
const authUrl = authsec.buildAuthorizeUrl({
response_type: 'code',
scope: 'openid profile ai:access',
redirect_uri: 'http://localhost:3000/callback'
});
window.location.href = authUrl;
}
// Handle callback
async function handleCallback(code) {
try {
const tokens = await authsec.exchangeCodeForTokens({
code: code,
redirect_uri: 'http://localhost:3000/callback'
});
// Store tokens securely
localStorage.setItem('access_token', tokens.access_token);
localStorage.setItem('refresh_token', tokens.refresh_token);
return tokens;
} catch (error) {
console.error('Token exchange failed:', error.message);
throw error;
}
}
3. Device Code Flow (Limited Input Devices)
For devices with limited input capabilities like AI assistants or IoT devices.
async function authenticateDevice() {
try {
// Start device authorization
const deviceAuth = await authsec.startDeviceAuthorization({
scope: 'openid profile ai:access'
});
// Display user code and verification URL to user
console.log(`Visit: ${deviceAuth.verification_uri}`);
console.log(`Enter code: ${deviceAuth.user_code}`);
// Poll for completion
const tokens = await authsec.pollForDeviceTokens({
device_code: deviceAuth.device_code,
interval: deviceAuth.interval
});
return tokens;
} catch (error) {
console.error('Device authentication failed:', error.message);
throw error;
}
}
User Management
Get User Information
// Get current user profile
async function getCurrentUser(accessToken) {
try {
const user = await authsec.getUserInfo(accessToken);
return user;
} catch (error) {
console.error('Failed to get user info:', error.message);
throw error;
}
}
Update User Profile
// Update user information
async function updateUserProfile(accessToken, updates) {
try {
const updatedUser = await authsec.updateUser(accessToken, {
given_name: updates.firstName,
family_name: updates.lastName,
picture: updates.avatarUrl,
user_metadata: updates.customData
});
return updatedUser;
} catch (error) {
console.error('Failed to update user:', error.message);
throw error;
}
}
Token Management
Validate Tokens
// Validate access token
async function validateToken(token) {
try {
const isValid = await authsec.validateToken(token);
return isValid;
} catch (error) {
console.error('Token validation failed:', error.message);
return false;
}
}
Refresh Tokens
// Refresh access token
async function refreshAccessToken(refreshToken) {
try {
const newTokens = await authsec.refreshToken({
refresh_token: refreshToken
});
// Update stored tokens
localStorage.setItem('access_token', newTokens.access_token);
if (newTokens.refresh_token) {
localStorage.setItem('refresh_token', newTokens.refresh_token);
}
return newTokens;
} catch (error) {
console.error('Token refresh failed:', error.message);
throw error;
}
}
Authorization Checks
Role-Based Access Control
// Check user permissions
async function checkPermission(accessToken, resource, action) {
try {
const hasPermission = await authsec.checkPermission(accessToken, {
resource: resource,
action: action
});
return hasPermission;
} catch (error) {
console.error('Permission check failed:', error.message);
return false;
}
}
// Example usage
const canGenerateAI = await checkPermission(token, 'ai:models', 'generate');
const canAccessMCP = await checkPermission(token, 'mcp:tools', 'execute');
Scope Validation
// Check if token has required scopes
function hasRequiredScopes(token, requiredScopes) {
const tokenScopes = authsec.getTokenScopes(token);
return requiredScopes.every(scope => tokenScopes.includes(scope));
}
// Example usage
const hasAIAccess = hasRequiredScopes(token, ['ai:generate', 'ai:analyze']);
Error Handling
Common Error Scenarios
// Comprehensive error handling
async function handleAuthsecOperation(operation) {
try {
return await operation();
} catch (error) {
switch (error.code) {
case 'INVALID_TOKEN':
// Token is invalid or expired
console.log('Token expired, attempting refresh...');
return await refreshAndRetry(operation);
case 'INSUFFICIENT_PERMISSIONS':
// User lacks required permissions
console.log('Access denied: insufficient permissions');
throw new Error('You do not have permission to perform this action');
case 'RATE_LIMIT_EXCEEDED':
// API rate limit exceeded
console.log('Rate limit exceeded, retrying after delay...');
await delay(error.retry_after * 1000);
return await operation();
case 'NETWORK_ERROR':
// Network connectivity issue
console.log('Network error, retrying...');
return await retryWithBackoff(operation);
default:
console.error('Unexpected error:', error.message);
throw error;
}
}
}
Best Practices
Security Best Practices
- Store Credentials Securely: Use environment variables or secure key management
- Validate Tokens: Always validate tokens before trusting them
- Use HTTPS: Ensure all communication is encrypted
- Handle Token Expiry: Implement automatic token refresh
- Principle of Least Privilege: Request only necessary scopes
Performance Best Practices
- Token Caching: Cache valid tokens to reduce API calls
- Connection Pooling: Reuse HTTP connections where possible
- Async Operations: Use asynchronous operations for better performance
- Error Retry Logic: Implement exponential backoff for retries
- Monitor Rate Limits: Track API usage to avoid rate limiting
Development Best Practices
- Environment Separation: Use different configurations for dev/staging/prod
- Logging: Log authentication events for debugging
- Testing: Write comprehensive tests for authentication flows
- Documentation: Document your integration and configuration
- Version Pinning: Pin SDK versions for consistent behavior
Troubleshooting
Common Issues
- Invalid Client ID/Secret: Verify credentials in Authsec dashboard
- Redirect URI Mismatch: Ensure callback URLs match configuration
- Scope Not Granted: Check if requested scopes are allowed for your client
- Token Expired: Implement proper token refresh logic
- CORS Issues: Configure allowed origins in client settings
Debug Mode
Enable debug logging for development:
// Enable debug mode
const authsec = new AuthsecClient({
domain: 'your-domain.authsec.com',
clientId: 'your-client-id',
clientSecret: 'your-client-secret',
debug: true // Enable debug logging
});
Getting Help
- Support: Contact support@authsec.com
- Community: Join our developer community
- GitHub: Report issues on our GitHub repository