API / Examples
OAuth callback
Handle the OAuth 2.0 redirect and exchange the authorization code for an access token.
This example shows how to handle the OAuth 2.0 callback when using the OAuth 2.0 user flow.
When a user authorises your application they are redirected back to your redirect URI with an authorization code. Your application handles that callback and exchanges the code for an access token.
const express = require('express');
const axios = require('axios');
const app = express();
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET; // store this securely
const REDIRECT_URI = process.env.REDIRECT_URI; // same redirect URI used in the authorize endpoint
app.get('/auth/callback', async (req, res) => {
console.log('Received callback with query:', req.query);
try {
const { code, error, error_description } = req.query;
// Handle errors
if (error) {
return res.status(400).json({
error: error,
error_description: error_description
});
}
if (!code) {
return res.status(400).json({ error: 'Authorization code not provided' });
}
// Optionally validate the state parameter here if you provided one in the authorize request
const params = new URLSearchParams();
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('client_id', CLIENT_ID);
params.append('client_secret', CLIENT_SECRET);
params.append('redirect_uri', REDIRECT_URI);
// Exchange authorization code for tokens
const tokenResponse = await axios.post('https://api.light.inc/oauth/token', params, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
});
// Store tokens in your database, preferably encrypted
// saveTokens(tokenResponse.data);
res.json({ success: true });
} catch (error) {
res.status(500).json(error.response?.data || { error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});