Coder Social home page Coder Social logo

nvh95 / react-linkedin-login-oauth2 Goto Github PK

View Code? Open in Web Editor NEW
93.0 5.0 48.0 2.58 MB

Easily get Authorization Code from Linked In to log in without redirecting.

License: MIT License

JavaScript 34.35% HTML 3.03% TypeScript 62.63%
react linkedin login signin oauth2 oauth linkedin-api hacktoberfest

react-linkedin-login-oauth2's Introduction

React Linked In Login Using OAuth 2.0

react-linkedin-login-oauth2 VERSION 2 IS OUT. THIS IS MIGRATION GUIDE FROM 1 TO 2.

All Contributors PRs Welcome

npm package npm

Demo: https://stupefied-goldberg-b44ee5.netlify.app/

This package is used to get authorization code for Linked In Log in feature using OAuth2 in a easy way. After have the authorization code, you can exchange to an access token by sending it to the server to continue to get information needed. For more details, please see at Authorization Code Flow (3-legged OAuth)
See Usage and Demo for instruction.

Table of contents

Changelog

See CHANGELOG.md

Installation

npm install --save react-linkedin-login-oauth2@latest

Overview

We will trigger linkedInLogin by using useLinkedIn (recommended) or LinkedIn (using render props technique) after click on Sign in with LinkedIn button, a popup window will show up and ask for the permission. After we accepted, the pop up window will redirect to redirectUri (should be LinkedInCallback component) then notice its opener about the authorization code Linked In provides us. You can use react-router-dom or Next.js's file system routing

Usage

First, we create a button and provide required props:

import React, { useState } from 'react';

import { useLinkedIn } from 'react-linkedin-login-oauth2';
// You can use provided image shipped by this package or using your own
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';

function LinkedInPage() {
  const { linkedInLogin } = useLinkedIn({
    clientId: '86vhj2q7ukf83q',
    redirectUri: `${window.location.origin}/linkedin`, // for Next.js, you can use `${typeof window === 'object' && window.location.origin}/linkedin`
    onSuccess: (code) => {
      console.log(code);
    },
    onError: (error) => {
      console.log(error);
    },
  });

  return (
    <img
      onClick={linkedInLogin}
      src={linkedin}
      alt="Sign in with Linked In"
      style={{ maxWidth: '180px', cursor: 'pointer' }}
    />
  );
}

If you don't want to use hooks. This library offer render props option:

import React, { useState } from 'react';

import { LinkedIn } from 'react-linkedin-login-oauth2';
// You can use provided image shipped by this package or using your own
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';

function LinkedInPage() {
  return (
    <LinkedIn
      clientId="86vhj2q7ukf83q"
      redirectUri={`${window.location.origin}/linkedin`}
      onSuccess={(code) => {
        console.log(code);
      }}
      onError={(error) => {
        console.log(error);
      }}
    >
      {({ linkedInLogin }) => (
        <img
          onClick={linkedInLogin}
          src={linkedin}
          alt="Sign in with Linked In"
          style={{ maxWidth: '180px', cursor: 'pointer' }}
        />
      )}
    </LinkedIn>
  );
}

Then we point redirect_url to LinkedInCallback. You can use react-router-dom or Next.js's file system routing

  • react-router-dom:
import React from 'react';
import { LinkedInCallback } from 'react-linkedin-login-oauth2';

import { BrowserRouter, Route } from 'react-router-dom';

function Demo() {
  return (
    <BrowserRouter>
      <Route exact path="/linkedin" component={LinkedInCallback} />
    </BrowserRouter>
  );
}
  • Next.js's file system routing:
// pages/linkedin.js
import { LinkedInCallback } from 'react-linkedin-login-oauth2';
export default function LinkedInPage() {
  return <LinkedInCallback />;
}

Support IE

  • Support for IE is dropped from version 2

Demo

Props

  • LinkedIn component:
Parameter value is required default
clientId string yes
redirectUri string yes
onSuccess function yes
onError function no
state string no randomly generated string (recommend to keep default value)
scope string no 'r_emailaddress'
See your app scope here. If there are more than one, delimited by a space
children function no Require if using LinkedIn component (render props)

Reference: https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context#step-2-request-an-authorization-code

  • LinkedInCallback component:
    No parameters needed

Issues

Please create an issue at https://github.com/nvh95/react-linkedin-login-oauth2/issues. I will spend time to help you.

Failed to minify the code from this file: ./node_modules/react-linkedin-login-oauth2/node_modules/query-string/index.js:8

Please upgrade react-linkedin-login-oauth2 to latest version following

npm install --save react-linkedin-login-oauth2

Known issue

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Hung Viet Nguyen

๐Ÿ’ป

Nguyแป…n Duy Khรกnh

๐Ÿ’ป

YBeck

๐Ÿ’ป

Mehdi Raza

๐Ÿค”

Phillip Denness

๐Ÿ›

dsp.iam

๐Ÿ›

Vitalii Bulyzhyn

๐Ÿ’ป

Pradeep Reddy Guduru

๐Ÿ›

Uric Bonatti Cardoso

๐Ÿ›

faisalur-rehman

๐Ÿ“–

Ruslan

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

react-linkedin-login-oauth2's People

Contributors

allcontributors[bot] avatar asanovr avatar nvh95 avatar songuku95 avatar vitalii-bulyzhyn avatar ybeck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-linkedin-login-oauth2's Issues

Module parse failed: Unexpected character '๏ฟฝ' (1:0)

Hello,
I installed react-linkedin-login-oauth2 and created the button as it was explained. However,
everytime I get the following error:

./node_modules/react-linkedin-login-oauth2/assets/linkedin.png 1:0
Module parse failed: Unexpected character '๏ฟฝ' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

My config:
"react-linkedin-login-oauth2": "^1.0.8",
"node": 12.16.1
"next": "9.3.6"

I don't have a webpack configured. I think its due to next.js but I'm not sure

Do you have any ideas on how I can fix this?

Thanks in advance :)

Issue with data

I have a problem getting the data (the code is displayed in the window but in console undefined)

Having problem with the popup close

Originally when I tried this module, I was getting a behaviour where after LinkedIn authorized, my return URL would render in the popup, rather than close and pass back the token. Then at one point it just started to work properly. Then I compiled and it went back to the original behaviour of not closing the popup.
I have embedded

the component in my own page (coverpage). And for debugging purposes taken your code and put it under my utilis folder, just so I can add console.log debugs and figure out whats going on.
I think it's in the eventlistener attachment, as I cannot see any of these events registered in the tools window attached to the document of the popup. But I am not sure. It could also have something todo with the browser router as I am embedding it in another page... I am not quite certain what the intent of the router is here.
Below you can see the code for the relevant files. let me know if you need anything else.
T
linkedin_debugging.zip
hanks- I have been pulling my hair out for 2 days on this.

The redirect_uri does not match the registered value

This error happen when the popup is open

I'm using:
NextJs 11.1.2
NodeJs 14.15.4

###screenshot:
image

Here is the popup url: https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=771x1e89b1ejnb&redirect_uri=http://localhost:3001/linkedin&scope=r_emailaddress&state=7ZSHiy6FfFVJt9KvhlBd

Here is the code:

import { useLinkedIn } from 'react-linkedin-login-oauth2';

import Button from '../Button';

const classes = {
  button: {
    paddingTop: 26,
    paddingBottom: 30,
  },
  icon: {
    marginRight: 12,
    width: 32
  },
};

const LinkedLogin = ({
  buttonText = 'Continuer avec LinkedIn',
  onSuccess, onFailure, loading,
}) => {
  const { linkedInLogin } = useLinkedIn({
    clientId: process.env.NEXT_PUBLIC_LINKEDIN_ID,
    redirectUri: `http://localhost:3001/linkedin`, // for Next.js, you can use `${typeof window === 'object' && window.location.origin}/linkedin`
    // scope: "r_emailaddress r_liteprofile",
    onSuccess: (code) => {
      onSuccess(code);
    },
    onError: (error) => {
      onFailure(error);
    },
  });

  return (
    <div className="flex1 stretchSelf flexCenter">
      <Button
        onClick={linkedInLogin}
        className="flexRow alignCenter smallText"
        icon={<img alt="google_logo" src="/icons/linkedin.png" css={classes.icon} />}
        type="default"
        fullWidth
        loading={loading}
        css={classes.button}
      >
        {buttonText}
      </Button>
    </div>
  );
};

export default LinkedLogin;

Failed to compile. error when building the create-react-app project

Hello, I see this error when trying to build create-react-app based project with this library:

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

 	./node_modules/react-linkedin-login-oauth2/node_modules/query-string/index.js:8

Read more here: http://bit.ly/2tRViJ9

state does not match issue

after clicking on the sign with the LinkedIn button login pop-up come and redirect to the "/linkedin" route with this error.
If anyone knows how to fix this issue please help.
image

How to exchange Authorization Code with Access Token

I'm trying to implement Linkedin Oauth2 according to this: https://developer.linkedin.com/docs/oauth2.

What I receive using this component onSuccess hook is Authorization Code but I need to exchange it with Access Token and then send the token to my server.

Making another POST: https://www.linkedin.com/oauth/v2/accessToken is returning CORS error:

Failed to load https://www.linkedin.com/oauth/v2/accessToken: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Thank you.

Not able to use more than once for Page and Profile both

Hi,

I want to use plugin to connect Page and Profile both so created different components for both and imported in same parent component.
Now click on any one to connect both components react on success and error case.
I'm using in NextJs

image

image

check the console log it create log for both components for success case.
any idea?

Thanks

Invalid access token

Hi guys,

When I'm getting the access token using Postman I receive a 350 character long token.

When I'm doing it using react-linkedin-login-oauth2 I receive a 211 character long token.

There is a length difference between the 2, the one from Postman is longer.

When I use the Postman token to query https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~)) it works properly but when I use the shorter token from react-linkedin-login-oauth2 I receive an error from linkedin:

{
  serviceErrorCode: 65600,
  message: 'Invalid access token',
  status: 401
}

Any idea what I could be doing wrong?

Thanks

Opening in new window

Hi! Is it possible to open LinkedIn as PopUp or as Iframe? Because now it opens new tab. I expected it like a pop up, but it works incorrectly. Can you please explain it for me?
image
image

Issue with scope

I haven't defined scope since it is not a required field but it still gives me this error.
error: "invalid_request" errorMessage: "You need to pass the "scope" parameter" from: "Linked In"

Token is not valid after success callback

I am able to get the token but when i use that token to generate refresh token it says { "error": "invalid_request", "error_description": "Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists" }

When i manually generate token using this https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=xxxxxxx&redirect_uri=https://localhost:3000 that token is working fine.

Client Credential Flow (2-legged OAuth)

In the library default behaviour is Authorization Code Flow (3-legged OAuth) is there a way we can switch to Client credential flow (2-legged OAuth) where we can get access token ?

Is there a way to embed linkedin login and permission granting redirection from codebase?

I have a requirement to display LinkedIn posts on clients' website. All I need to get is Auth code. By using 'react-linkedin-login-oauth2' package am able to get the 'code''easily by providing linkedin login credentials and allowing permissions, but the client doesn't want to provide login credentials and permission allowing button click on website? Is there a way to embed LinkedIn login and permission granting pages redirection from codebase by hardcoding username and password info using 3 legged Oauth?

Having issue with popup

I just tried your react-linkedin-login-oauth2 through npm. I'm able to log in through linked in perfectly but after login, the redirect URL happening in the popup instead of the parent window.

I tried this.
``````

            <LinkedIn
                    clientId="xxxxxxxxxxxxxxxx"
                    redirectUri={`${`http://localhost:3004/#/login`}/linkedin`}
                    onFailure={this.handleFailure}
                    onSuccess={this.handleSuccess}
                  >
                   Login with linkedin
             </LinkedIn>

unexpected token

.btn-linkedin {
^

SyntaxError: Unexpected token .
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)

Error 'Unable to resolve module react/jsx-runtime' when running the app

Hello,

I have the following error on both Android and iOS when running the app:

error: Error: Unable to resolve module react/jsx-runtime from /Users/myUser/Documents/myApp/node_modules/react-linkedin-login-oauth2/build/index.js: react/jsx-runtime could not be found within the project.

With:

  • React 16.13.1
  • React Native 0.63.5
  • React LinkedIn Login oAuth2 2.0.1

I cannot find where it comes from.

Thanks

Edit: OK I'm dumb, I tried to use it with React Native.

onSuccess is called twice

When I get the authorization code from the onSuccess callback, I will try to retrieve an access token from LinkedIn. However, I found that the onSuccess callback is always called twice with the same authorization code. It will trigger my function to LinkedIn twice causing LinkedIn to return an error saying my authorization code is expired in the second call.

Is it intented?

react-linkedin-login-oauth2 not working with nextjs

Server Error
SyntaxError: Invalid or unexpected token
when i try to implement linkedIn login this error is coming.

error:-
Uncaught at (file:///home/user/Desktop/project-nextjs/node_modules/react-linkedin-login-oauth2/assets/linkedin.png:1)
at Object.compileFunction (node:vm:355:18)
at wrapSafe (node:internal/modules/cjs/loader:1038:15)
at Module._compile (node:internal/modules/cjs/loader:1072:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:988:32)
at Function.Module._load (node:internal/modules/cjs/loader:828:14)
at Module.require (node:internal/modules/cjs/loader:1012:19)
at require (node:internal/modules/cjs/helpers:93:18)
at Object. (file:///home/netzwelt/Desktop/artmo-nextjs/node_modules/react-linkedin-login-oauth2/lib/LinkedIn.js:163:57)
at Module._compile (node:internal/modules/cjs/loader:1108:14)

Could not find a declaration file for module 'react-linkedin-login-oauth2'.

I'm working on a reactJs project using Material-UI and there's neither Typescript. nor 'tsconfig.json' file in my project.
I tried this module 5 days back and it worked fine. But now, I'm getting the below error after the '1.0.8' release.

Could not find a declaration file for module 'react-linkedin-login-oauth2'. '/Users/pg185136/Desktop/RethinkingUX/Website/BitBucket/rethinkingux/node_modules/react-linkedin-login-oauth2/lib/index.js' implicitly has an 'any' type.
Try npm install @types/react-linkedin-login-oauth2 if it exists or add a new declaration (.d.ts) file containing declare module 'react-linkedin-login-oauth2';ts(7016)

I've gone thru this blog on this issue but as my project is not in typescript, I can't even apply any of these fixes. Lemme know if I'm missing anything.
Any help is much appreciated.
@YBeck @nvh95 @Songuku95 @jaykrs

Security Issue - state was removed and generated randomly , which exposes CSRF attack .

The state was removed and generated randomly, which exposes CSRF attack.

previously state was an optional field and was entirely removed on this commit 4274b93?short_path=b335630#r58595171

with the removal, it makes it impossible for the backend server to generate a state for that user and validate it .

the state should be brought back as optional. since most of us where already passing the state as a prop. which are validated at the backend , generating a random state exposes a security issue .

Kindly check out linked auth documentation

https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin%2Fconsumer%2Fcontext&tabs=HTTPS

Issue to get the accessToken using the code from this module

I got the code from the response data using this module, and tried to get the accessToken using that code, but got the error.
My code and the error like followings;

Linkedin tag

<LinkedIn response_type='code' clientId="7766ia9vsfbyxb" scope='r_emailaddress+r_liteprofile' redirectUri='https://dev.d9jruxpfxzt30.amplifyapp.com/home' onFailure={this.handleFailure} onSuccess={this.handleSuccess} />

request to get the accessToken

  `let config = {
    method: 'post',
    url: `https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code=${data.code}&redirect_uri=https://dev.d9jruxpfxzt30.amplifyapp.com/home&client_id=7766ia9vsfbyxb&client_secret=GKCUsY4o71dYd0iJ`,
    headers: { 
      'Content-Type': 'application/x-www-form-urlencoded',
    }
  };`

#I have tested this request in Postman, following is the error in postman:
{
"error": "invalid_request",
"error_description": "Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists"
}

onSuccess/onFailure doesn't pass anything

I'm using react hooks and passing data to another function using onSuccess={myfunc} and onFailuire.

`const handleSuccess = (data) => {
console.log(data); //no passed data here
}

return(
<img alt="Log in with Linked In" style={{ maxWidth: '180px' }} />
)`

Another approach is to pass directly the function but still no luck.
<LinkedIn clientId={env.LINKEDIN_CLIENT_ID()} onFailure={(data) => {console.log(data)} } onSuccess={(data) => {console.log(data)} } scope="r_liteprofile r_emailaddress" redirectUri="http://localhost:3000/auth/linkedin" > <img alt="Log in with Linked In" style={{ maxWidth: '180px' }} /> </LinkedIn>

works fine in here https://www.npmjs.com/package/react-linkedin-oauth2

Cannot be used with React 17

I'm trying to use package with React 17.0.2, however it requires React 16.x

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"16.x" from [email protected]
npm ERR! node_modules/react-linkedin-login-oauth2
npm ERR! react-linkedin-login-oauth2@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /home/vitalii/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/vitalii/.npm/_logs/2021-05-17T19_43_13_791Z-debug.log

Popup does not close even if the login is successful or user presses cancel button. It redirects me back to origin url without closing the popup.

Popup does not close even if the login is successful or user presses cancel button. It redirects me back to origin url without closing the popup. Here is my code:

import React, { useState } from "react";

import { useLinkedIn } from "react-linkedin-login-oauth2";
// You can use provided image shipped by this package or using your own
// import linkedin  from "react-linkedin-login-oauth2";

export default function LinkedInPage() {
  const { linkedInLogin } = useLinkedIn({
    clientId: "{my_client_id}",
    redirectUri: `${window.location.origin}/linkedin`,
    onSuccess: (code) => {
      console.log(code);
    },
    onError: (error) => {
      console.log(error);
    },
  });

  return (
    <img
      onClick={linkedInLogin}
      //   src={linkedin}
      alt="Sign in with Linked In"
      style={{ maxWidth: "180px", cursor: "pointer" }}
    />
  );
}

After Popup closes, my main app background image disappears (blank)

As the title says, the problem comes after log in successfully, the popup window will close and successfully send me the code to my main reactjs application but at the same time, it also makes my background image and some icons disappear. Why is this? I simply implemented the code displayed in the description.

index.js

import { LinkedInPopUp } from 'react-linkedin-login-oauth2';
<Route exact path="/linkedin" component={LinkedInPopUp} /> 

oauth.js

import { LinkedIn } from "react-linkedin-login-oauth2";

handleLinkedInFailure = (response) => {
     console.log("linkedinfailure", response);
   };
   handleLinkedInSuccess = (response) => {
     console.log("linkedinsuccess", response);
   };

<LinkedIn
                 clientId="XXX"
                 onFailure={this.handleLinkedInFailure}
                 onSuccess={this.handleLinkedInSuccess}
                 redirectUri="http://localhost:3000/linkedin"
                 renderElement={({ onClick, disabled }) => (
                   <Button
                     icon={<IconFont type="icon-linkedin" />}
                     onClick={onClick}
                     disabled={disabled}
                   >
                     Log in with Linkedin
                   </Button>
                 )}
               />

Issue on Linkedin Oauth ( ! netlify in production mode)

Hey there! I have an issue with Linkedin auth.
While working with the local server there is no issue it's working perfectly fine. But when it goes to netlify after logging through LinkedIn it not redirected to the home page instead it gives some error.

Screen shot of Error page

image

Does anyone have a solution for it?

Issue with scope after clicking on linkedin button

Seeing an issue after clicking on the LinkedIn button.

Steps:

  1. started the app using "npm start"
  2. app started on "localhost:3000"
  3. seeing message on the page after clicking on LinkedIn button to login (had logged into the Linkedin on different page)

Message displayed:

"No code
Scope "r_fullprofile" is not authorized for your application"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.