How to Add LinkedIn OAuth in your ReactJs LinkedIn Authentication Process


Hello, fellow devs❤! 

Are you stuck with your React app's LinkedIn oauth signup process? Don't worry, I've got your back! Incorporating LinkedIn OAuth into your React application's signup process allows users to authenticate using their LinkedIn accounts, expedites the registration process, and improves user experience. 

This guide provides step-by-step instructions for integrating LinkedIn OAuth into your React application, complete with code examples.

What Should We Have Beforehand?

  • Basic Concept of OAuth
  • An active LinkedIn profile
  • A LinkedIn OAuth application registered and configured
  • Proficiency in JavaScript and React
  • Node.js and npm installed on your development environment

What is OAuth?

Let's do a quick recap on how OAuth works✋:

User Authorization: The user initiates the process by clicking a "Login" button on the client application.

Redirect to Authorization Server: The client application sends the specified scopes and client ID together with the user to the authorization server (such as Google or LinkedIn in this case).

User Authentication: After logging in, if they haven't previously, the user is asked to provide permission for the client system to access their data.

Authorization Grant: The user is redirected to the redirect URI of the client application by the authorization server, which also creates an authorization code or access token upon authorization.

Token Exchange: To exchange an access token for an authorization code, the client application sends a request to the authorization server.

Access Token: The authorization server validates the authorization code and issues an access token to the client application.

Resource Access: The client application uses the access token to make authorized requests to the resource server (e.g., LinkedIn API) on behalf of the user.

Data Retrieval: The resource server validates the access token and, if valid, returns the requested user data to the client application.



Source

Getting Started with LinkedIn OAuth Social Login with ReactJs

Step 1: Register your App on the LinkedIn Developers Portal

To begin integrating LinkedIn OAuth into your application, the first step is to register your application on the LinkedIn Developers portal.

Once there, provide the necessary information and click 'Create app' to generate your app credentials. 



Step 2: Get your Client ID and Client Secret

Within your app settings, navigate to the 'Auth' tab where you'll set the Redirect URL to specify where users will be redirected post-authentication. 

Make sure to copy the 'Client ID' and 'Client Secret' provided by LinkedIn, as they will be required for the authentication process later on. 



Step 3: Create LinkedIn OAuth Component in your ReactJs src Folder

My React component enables users to authenticate with their LinkedIn accounts using OAuth 2.0. It initiates the authentication process by redirecting users to LinkedIn's authorization page. 

After successful authentication, it exchanges the authorization code for an access token. Then, it fetches the user's LinkedIn profile data and handles it accordingly, such as storing it in the database or logging the user in. 

Finally, it renders a 'Sign in with LinkedIn' button, triggering the authentication flow when clicked.

import React, { useEffect } from 'react';

const LinkedInSocialLogin = () => {
  const LINKEDIN_CLIENT_SECRET = 'your_client_secret';
  const LINKEDIN_CLIENT_ID = 'your_client_id';
  const LINKEDIN_CALLBACK_URL = 'http://localhost:3000/auth/linkedin/callback';
  const linkedinOAuthURL = `https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${LINKEDIN_CLIENT_ID}&redirect_uri=${encodeURIComponent(
    LINKEDIN_CALLBACK_URL
  )}&scope=r_liteprofile%20r_emailaddress`;

  const handleLogin = async (code) => {
    const response = await fetch('https://www.linkedin.com/oauth/v2/accessToken', {
      method: 'POST',
      body: new URLSearchParams({
        grant_type: 'authorization_code',
        code,
        redirect_uri: LINKEDIN_CALLBACK_URL,
        client_id: LINKEDIN_CLIENT_ID,
        client_secret: LINKEDIN_CLIENT_SECRET
      })
    });
    const data = await response.json();
    const accessToken = data.access_token;

    const userProfileResponse = await fetch(
      'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)',
      {
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      }
    );
    const userProfile = await userProfileResponse.json();

    console.log(`Welcome, ${userProfile.localizedFirstName} ${userProfile.localizedLastName}!`);
  };

  useEffect(() => {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const code = urlParams.get('code');
    if (code) handleLogin(code);
  }, []);

  return (
    
  );
};

export default LinkedInSocialLogin;


Step 4: Add your LinkedIn OAuth Component in your app.js File

I imported my LinkedInSocialLogin into my app.js to render my component. The LinkedInSocialLogin component and header are displayed when the application loads, making it easier for users to authenticate on LinkedIn. 

import React from 'react';
import LinkedInSocialLoginfrom './LinkedInSocialLogin';
const App = () => ( LinkedIn Social Login Example
); export default App;


Step 5: Run your Application

After setting up the LinkedIn OAuth integration and implementing it into your React application, it's time to run the app. 

By executing the React application, it will be hosted locally at http://localhost:3000/. This local server allows you to test the LinkedIn OAuth login functionality easily.

Frequently Asked Questions

How do I get a LinkedIn token?

Go to the LinkedIn Developers Portal, click on the 'Create App' tab, and then you have to fill up all the necessary details. In the auth tab, you will find your LinkedIn token and client ID.

How do I integrate my LinkedIn login?

Get your LinkedIn client secret and client ID from the developer portal, then create your component with all the credentials and connect your component with app.js.

Can I use LinkedIn API for free?

Yes, you can use LinkedIn API for free for now.

codegirl

Hello! I'm a Developer with a strong passion for coding and writing. My expertise lies in creating scalable web applications using leading-edge technologies. I am proficient in various programming languages, including Java, SQL, Mongodb, Express Js, Node JS, React Js and Next.js. Beyond coding, I shine in the world of technical content writing, using my knowledge to create engaging and informative articles.

Post a Comment

Previous Post Next Post