Skip to content

Authentication

The Stack Overflow SDK provides built-in authentication helpers that simplify the OAuth 2.0 flow with PKCE for secure token generation. Authentication requirements vary by Stack Overflow for Teams tier.

  • Stack Overflow for Teams Enterprise - Supports OAuth 2.0 with PKCE. Access tokens can be generated dynamically. You can optionally provide a single Access Token manually.
  • Stack Overflow for Teams Basic/Business - OAuth is not available. Manual input of Access tokens (PATs) are required in order to use the SDK.

The SDK includes two authentication clients for Enterprise instances:

  • BackendAuthClient - For server-side Node.js environments with full PKCE implementation
  • FrontendAuthClient - For browser environments that communicate with your backend API
import StackOverflowSDK from '@stackoverflow/teams-sdk';
// Option 1: OAuth configuration (no token required initially)
const sdk = new StackOverflowSDK({
baseUrl: 'https://your-site.stackenterprise.co',
auth: {
clientId: 'your-client-id',
redirectUri: 'https://yourapp.com/callback',
baseUrl: 'https://your-site.stackenterprise.co',
scope: 'read_inbox write_access'
}
});
// Option 2: With existing access token
const sdk = StackOverflowSDK.fromToken(
'your-access-token',
'https://your-site.stackenterprise.co'
);
// Option 3: Factory method for OAuth setup
const sdk = StackOverflowSDK.enterpriseOAuth({
clientId: 'your-client-id',
redirectUri: 'https://yourapp.com/callback',
baseUrl: 'https://your-site.stackenterprise.co'
});

Basic/Business - Personal Access Token Required

Section titled “Basic/Business - Personal Access Token Required”
import StackOverflowSDK from '@stackoverflow/teams-sdk';
// PAT is mandatory for Basic/Business tiers
const sdk = StackOverflowSDK.fromToken(
'your-personal-access-token',
'https://api.stackoverflowteams.com/v3'
);
// Team context is required for Basic/Business operations
const teamContext = sdk.forTeam('your-team-id');
const questions = await teamContext.questions.getAll();

The BackendAuthClient handles the complete OAuth flow with PKCE on your server:

backend-auth.ts
import { BackendAuthClient } from '@stackoverflow/teams-sdk';
const authClient = new BackendAuthClient({
clientId: 'your-client-id',
redirectUri: 'https://yourapp.com/callback',
baseUrl: 'https://your-site.stackenterprise.co',
scope: 'read_inbox write_access' // Optional
});
// Generate authorization URL
const { url, codeVerifier, state } = await authClient.getAuthUrl();
// Store codeVerifier and state securely (session, database, etc.)
// Redirect user to the authorization URL
// In your callback handler:
const tokens = await authClient.exchangeCodeForToken(
callbackCode,
storedCodeVerifier
);
// Validate state for CSRF protection
const isValidState = authClient.validateState(callbackState, storedState);

The FrontendAuthClient communicates with your backend API to handle OAuth securely:

frontend-auth.ts
import { FrontendAuthClient } from '@stackoverflow/teams-sdk';
const frontendClient = new FrontendAuthClient({
clientId: 'your-client-id',
redirectUri: 'https://yourapp.com/callback',
baseUrl: 'https://your-site.stackenterprise.co'
}, '/api'); // Your backend API base URL
// Start authentication flow
const authUrl = await frontendClient.startAuth();
window.location.href = authUrl;
// Handle OAuth callback
await frontendClient.handleCallback();
// Check authentication status
const isAuthenticated = await frontendClient.getAuthStatus();
// Manual token submission (for PATs)
const success = await frontendClient.submitAccessToken(userToken);
interface AuthConfig {
/** OAuth client ID from Stack Overflow Enterprise */
clientId: string;
/** Redirect URI registered with your application */
redirectUri: string;
/** Stack Overflow Enterprise instance URL */
baseUrl: string;
/** OAuth scopes (optional) */
scope?: string;
}
MethodDescriptionReturns
generatePKCETokens()Generate PKCE tokens for secure OAuthPromise<PKCETokens>
getAuthUrl()Generate authorization URL with PKCEPromise<{url, codeVerifier, state}>
exchangeCodeForToken()Exchange auth code for access tokenPromise<TokenResponse>
validateState()Validate state parameter for CSRF protectionboolean
MethodDescriptionReturns
startAuth()Start OAuth flow via backend APIPromise<string>
completeAuth()Complete OAuth with callback paramsPromise<void>
handleCallback()Handle OAuth callback in current pagePromise<void>
getAuthStatus()Check if user is authenticatedPromise<boolean>
submitAccessToken()Submit manual access tokenPromise<boolean>
logout()Clear authentication statePromise<boolean>

Different API operations require different scopes:

ScopeDescription
read_inboxAccess user’s inbox
write_accessPerform write operations
private_infoAccess private user data
no_expiryToken never expires (use with caution)

PKCE Implementation

The SDK automatically implements PKCE (Proof Key for Code Exchange) to prevent authorization code interception attacks.

State Validation

Always validate the state parameter in OAuth callbacks to prevent CSRF attacks using the built-in validation methods.

Secure Token Storage

Follow secure token storage best practices and avoid client-side storage for sensitive authentication data.

Environment Variables

Keep sensitive configuration like client IDs and secrets in environment variables, not in your source code.

Handle authentication errors gracefully:

auth-error-handling.ts
async function authenticateUser() {
try {
const authUrl = await authClient.getAuthUrl();
// Handle success
} catch (error) {
if (error.message.includes('clientId')) {
console.error('Missing OAuth configuration');
} else {
console.error('Authentication setup failed:', error);
}
}
}
// In callback handler
try {
const tokens = await authClient.exchangeCodeForToken(code, codeVerifier);
} catch (error) {
if (error.message.includes('Failed to exchange')) {
console.error('Token exchange failed - check OAuth configuration');
}
throw error;
}

For simpler Enterprise implementations, you can generate Tokens manually and use them as seen below:

const sdk = StackOverflowSDK.fromToken(
'your-enterprise-pat',
'https://your-site.stackenterprise.co'
);
const questions = await sdk.questions.getAll();

You’ll need to follow this guide to understand how OAuth works on Enterprise.

For Basic and Business tiers, PATs are the only authentication method available:

Personal Access Tokens (PATs) for API Authentication →

const sdk = StackOverflowSDK.fromToken(userProvidedPAT, 'https://api.stackoverflowteams.com/v3');
const teamContext = sdk.forTeam('team-123');

Once you have authentication configured with the helpers: