Back

How to build a public LinkedIn integration: Building the Auth Flow

Aug 1, 20246 minute read

Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of LinkedIn integrations? Today, we're focusing on the crucial part of any LinkedIn API integration: the authorization flow. Let's get started!

Prerequisites

Before we jump in, make sure you've got:

  • A LinkedIn Developer account
  • A registered application on the LinkedIn Developer Portal
  • Node.js and your favorite web framework (I'm partial to Express, but you do you!)

Setting up the project

First things first, let's get our project set up:

npm init -y npm install express axios dotenv

Now, let's create a basic server:

require('dotenv').config(); const express = require('express'); const app = express(); app.listen(3000, () => console.log('Server running on port 3000'));

LinkedIn OAuth 2.0 Flow Overview

LinkedIn uses OAuth 2.0 for authentication. In a nutshell, we'll redirect users to LinkedIn, they'll grant permissions, and LinkedIn will send us back an authorization code. We'll exchange this code for an access token, which we'll use for API calls. Easy peasy!

Implementing the Authorization Flow

Generate Authorization URL

Let's create a route to kick off the auth process:

const LINKEDIN_AUTH_URL = 'https://www.linkedin.com/oauth/v2/authorization'; app.get('/auth/linkedin', (req, res) => { const authUrl = `${LINKEDIN_AUTH_URL}?response_type=code&client_id=${process.env.LINKEDIN_CLIENT_ID}&redirect_uri=${encodeURIComponent(process.env.REDIRECT_URI)}&scope=r_liteprofile%20r_emailaddress`; res.redirect(authUrl); });

Handle the Callback

Now, let's set up a route to handle LinkedIn's callback:

const axios = require('axios'); app.get('/auth/linkedin/callback', async (req, res) => { const { code } = req.query; try { const { data } = await axios.post('https://www.linkedin.com/oauth/v2/accessToken', null, { params: { grant_type: 'authorization_code', code, redirect_uri: process.env.REDIRECT_URI, client_id: process.env.LINKEDIN_CLIENT_ID, client_secret: process.env.LINKEDIN_CLIENT_SECRET } }); // Store data.access_token securely res.send('Authentication successful!'); } catch (error) { console.error('Error during token exchange:', error); res.status(500).send('Authentication failed'); } });

Token Management

You'll want to store that access token securely. Consider using encrypted session storage or a secure database. Don't forget to implement a refresh mechanism - LinkedIn access tokens typically expire after about 60 days.

Making Authenticated Requests

Now that we have our access token, let's use it to make an API call:

async function getProfile(accessToken) { try { const { data } = await axios.get('https://api.linkedin.com/v2/me', { headers: { Authorization: `Bearer ${accessToken}` } }); return data; } catch (error) { console.error('Error fetching profile:', error); } }

Error Handling and Edge Cases

Always be prepared for things to go wrong. Common issues include expired tokens, network errors, or API changes. Implement robust error handling and consider using a library like axios-retry for automatic retries on failed requests.

Security Considerations

Remember, with great power comes great responsibility. Always use HTTPS, never expose your client secret, and consider implementing PKCE (Proof Key for Code Exchange) for added security.

Conclusion

And there you have it! You've just built the foundation for a LinkedIn integration. From here, you can expand to use more of LinkedIn's API endpoints, implement more robust token management, or even build a full-fledged LinkedIn-powered application.

Additional Resources

Happy coding, and may your connections be ever growing!