|

|  How to Implement LinkedIn OAuth 2.0 Authentication in Node.js

How to Implement LinkedIn OAuth 2.0 Authentication in Node.js

October 31, 2024

Master LinkedIn OAuth 2.0 in Node.js with this step-by-step guide. Enhance app security, streamline authentication, and boost user experience effortlessly.

How to Implement LinkedIn OAuth 2.0 Authentication in Node.js

 

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.

 

Pre-order Friend AI Necklace

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI Necklace

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

team@basedhardware.com

company

about

careers

invest

privacy

products

omi

omi dev kit

personas

resources

apps

affiliate

docs

github

help