Set Up the LinkedIn App
- Create a new LinkedIn application to obtain your client ID and client secret. These are required for OAuth authentication.
- Ensure that you set the Redirect URL in your LinkedIn app settings. This URL is where LinkedIn will redirect users after they authorize your app. Make sure this is a route you have planned to handle within your Node.js server.
Install Required Packages
- You'll need a couple of npm packages like `express`, `axios`, and `jsonwebtoken`. Express will help you set up the web server, axios will be used for HTTP requests, and jsonwebtoken will handle JWTs if needed.
npm install express axios jsonwebtoken
Create the Express Server
- Set up a basic Express server where you'll handle the OAuth flow. You'll need routes for the authentication request and the callback URL.
const express = require('express');
const axios = require('axios');
const app = express();
const CLIENT_ID = 'Your LinkedIn Client ID';
const CLIENT_SECRET = 'Your LinkedIn Client Secret';
const REDIRECT_URI = 'http://localhost:3000/auth/linkedin/callback';
app.get('/auth/linkedin', (req, res) => {
const linkedinAuthUrl = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&state=123456&scope=r_liteprofile%20r_emailaddress`;
res.redirect(linkedinAuthUrl);
});
app.get('/auth/linkedin/callback', async (req, res) => {
const code = req.query.code;
try {
const tokenResponse = await axios.post('https://www.linkedin.com/oauth/v2/accessToken', null, {
params: {
grant_type: 'authorization_code',
code: code,
redirect_uri: REDIRECT_URI,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
},
});
const accessToken = tokenResponse.data.access_token;
// You're almost there; now make API calls with this token.
res.json({ accessToken });
} catch (error) {
res.status(500).send(error.response.data);
}
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Fetch the User Profile
- With the obtained access token, make a request to LinkedIn's API to fetch the user profile data.
app.get('/getProfile', async (req, res) => {
// Replace with your token storage/management mechanism
const accessToken = 'User Access Token';
try {
const profileResponse = await axios.get('https://api.linkedin.com/v2/me', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
res.json(profileResponse.data);
} catch (error) {
res.status(500).send(error.response.data);
}
});
Debug and Test
- Test the entire flow starting by visiting the `/auth/linkedin` route to handle the authentication.
- Trace any issues that occur in the OAuth flow by checking console logs. Debugging tools and breakpoints can also help in understanding any roadblocks.
Security Considerations
- Ensure your Redirect URI is secure, preferably using HTTPS to prevent interception of the code parameter in the callback.
- Store access tokens securely, as they provide access to the user's profile data.