This example demonstrates how to handle the OAuth 2.0 callback when using the OAuth 2.0 user flow with the Light API.When a user authorizes your application, they will be redirected back to your specified redirect URI with an authorization code. You need to handle this callback in your application to exchange the authorization code for an access token.
Copy
Ask AI
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 securelyconst REDIRECT_URI = process.env.REDIRECT_URI; // same redirect URI used in the authorize endpointapp.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}`);});