My react code
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
const [profile, setProfile] = useState(null);
const handleLogin = () => {
// Redirect to LinkedIn login
window.location.href = 'http://localhost:5000/auth/linkedin';
};
// Fetch user profile from backend after successful login
const fetchProfile = async () => {
try {
const response = await axios.get('http://localhost:5000/auth/user'); // This will now fetch the profile
setProfile(response.data.user);
} catch (error) {
console.error('Error fetching profile', error);
}
};
useEffect(() => {
// Fetch the profile when the component mounts
fetchProfile();
}, []);
return (
<div className="container mt-5">
<h1 className="text-center">LinkedIn Login Demo</h1>
{!profile ? (
<div className="d-flex justify-content-center">
<button className="btn btn-primary" onClick={handleLogin}>Login with LinkedIn</button>
</div>
) : (
<div className="profile mt-5">
<h3>Profile Details:</h3>
<p><strong>Name:</strong> {profile.firstName} {profile.lastName}</p>
<p><strong>Email:</strong> {profile.email}</p>
</div>
)}
</div>
);
}
export default App;
my node js server code:
const express = require('express');
const passport = require('passport');
const LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
const axios = require('axios');
const router = express.Router();
// LinkedIn App Credentials
const LINKEDIN_CLIENT_ID = 'weqe'; // Replace with your actual Client ID
const LINKEDIN_CLIENT_SECRET = 'eqwe'; // Replace with your actual Client Secret
const CALLBACK_URL = 'http://localhost:5000/auth/linkedin/callback';
// Configure passport to use LinkedIn Strategy
passport.use(new LinkedInStrategy({
clientID: LINKEDIN_CLIENT_ID,
clientSecret: LINKEDIN_CLIENT_SECRET,
callbackURL: CALLBACK_URL,
scope: ['openid', 'profile', 'email','w_member_social'], // Updated scopes
state: true,
passReqToCallback: true // This ensures the callback gets the request object
},
async function(req, accessToken, refreshToken, profile, done) {
try {
// Fetching user profile from LinkedIn API manually
const profileResponse = await axios.get('https://api.linkedin.com/v2/userinfo', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
// Fetching user email address
const emailResponse = await axios.get('https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))', {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
const userProfile = {
id: profileResponse.data.id,
firstName: profileResponse.data.localizedFirstName,
lastName: profileResponse.data.localizedLastName,
email: emailResponse.data.elements[0]['handle~'].emailAddress
};
// Pass the profile data and token to the callback
return done(null, { profile: userProfile, token: accessToken });
} catch (error) {
console.error('Error fetching profile or email from LinkedIn:', error.message);
return done(error);
}
}
));
// Serialize and Deserialize user
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((obj, done) => {
done(null, obj);
});
// LinkedIn login route
router.get('/linkedin', passport.authenticate('linkedin'));
// Callback route after LinkedIn login
router.get('/linkedin/callback', passport.authenticate('linkedin', {
failureRedirect: '/login',
session: false,
}), (req, res) => {
// Send user profile and token as response
res.json({
message: 'Successfully logged in with LinkedIn',
user: req.user.profile,
token: req.user.token
});
});
// Add the /auth/user route to send user profile to frontend
router.get('/user', (req, res) => {
if (req.user) {
res.json({
user: req.user.profile,
});
} else {
res.status(401).send('Unauthorized');
}
});
module.exports = router;
my node package.json file
"dependencies": {
"axios": "^1.7.7",
"express": "^4.20.0",
"express-session": "^1.18.0",
"nodemon": "^3.1.4",
"passport": "^0.7.0",
"passport-linkedin-oauth2": "github:auth0/passport-linkedin-oauth2#v3.0.0"
}
i have written code some from chatgpt and some from stack overflow.
At first i was facing issue of not fetching user profile.
after updating passport-linkedin-oauth2 package now im getting this error
AxiosError: Request failed with status code 403
I think there some issue on LinkedIn side may be I’m wrong because for the error which I was getting previously I made changes in the package version.
Kindly help out to find exactly what the issue is.
I’m new to this social login. I’m first starting with the LinkedIn as I have to start my project with this step