Linkedin OAuth 2.0 in ionic 3

I’m trying to integrate LinkedIn(sign-in with) in ionic using Oauth 2.0 as it described in this website. This is my code

linkedinLogin() {
    this.platform.ready().then(() => {
      this.linkedinPage().then(success => {
        alert(success.access_token);
      },(error) => {
        alert(error);
      });
    });
  }

  linkedinPage(): Promise<any> {
    return new Promise(function(resolve, reject) {
      var browserRef = window.cordova.InAppBrowser.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=xxxxxxxxx&redirect_uri=http://localhost/callback&state=xxxxx&scope=r_basicprofile");
      browserRef.addEventListener("loadstart", (event) => {
          if ((event.url).indexOf("http://localhost/callback") === 0) {
              browserRef.removeEventListener("exit", (event) => {});
              browserRef.close();
              var responseParameters = ((event.url).split("#")[1]).split("&");
              var parsedResponse = {};
              for (var i = 0; i < responseParameters.length; i++) {
                  parsedResponse[responseParameters[i].split("=")[0]] = responseParameters[i].split("=")[1];
              }
              if (parsedResponse["access_token"] !== undefined && parsedResponse["access_token"] !== null) {
                  resolve(parsedResponse);
              } else {
                  reject("Problem authenticating with linkedin");
              }
          }
      });
      browserRef.addEventListener("exit", function(event) {
          reject("The linkedin sign in flow was canceled");
      });
  });
  }

I’m able to redirect to LinkedIn login page. After allowing the permissions it is throwing the error(in the code) as The linkedin sign in flow was canceled . How can I solve this problem? I want to display the details that I have received from the LinkedIn in the alert box.

Did you manage to solve it? I’m trying to do something similar

Continuing the discussion from Linkedin OAuth 2.0 in ionic 3:

Hi,
This is the sample code for linkedin login. You need to provide the following parameters:
REDIRECT_URI
CLIENT_ID
CLIENT_SECRET
STATE

Also, you need to declare cordova, like mentoned below :
declare var cordova: any;

and also import the following:
import { Http, Headers, RequestOptions } from ‘@angular/http’;

Also, you must have inappbrowser plugin installed.

linkLogin() {
    this.platform.ready().then(() => {
        this.linkedInLogin().then(success => {  
            let headers = new Headers({
                'Content-Type': 'application/x-www-form-urlencoded'
            });
            let options = new RequestOptions({
                headers: headers
            });
            var data: any;
            data = "grant_type=authorization_code&code=" + success.code + "&redirect_uri=<REDIRECT_URI>&client_id=<CLIENT_ID>&client_secret=<CLIENT_SECRET>";
            let body = data;
            this.http.post("https://www.linkedin.com/oauth/v2/accessToken", body, options).toPromise()
            .then(res => {
                let result = res.json();
                if (result["access_token"] !== undefined) {
                    this.getLinkedInUserDetails(result["access_token"]).then(response => {
                        console.log("response is the JSON containing the user details from Linkedin.")
                    }).then(() => {
                    });
                } else {
                }
            }, err => {
                console.log("Failed");
            });
        }, (error) => {
            console.log("error : " + error);
        });
    });
}

linkedInLogin(): Promise<any> {
    return new Promise(function (resolve, reject) {
        var uri = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=<CLIENT_ID>&" + "redirect_uri=<REDIRECT_URI>&state=<STATE>&scope=r_basicprofile%20r_emailaddress";
        var browserRef = cordova.InAppBrowser.open(uri);
        browserRef.addEventListener("loadstart", (event) => {
            if ((event.url).indexOf(<REDIRECT_URI>) === 0) {
                browserRef.removeEventListener("exit", (event) => { });
                browserRef.close();
                var parsedResponse = {};
                var code = (event.url.split("=")[1]).split("&")[0];
                var state = event.url.split("=")[2];
                if (code !== undefined && state !== null) {
                    parsedResponse["code"] = code;
                    resolve(parsedResponse);
                } else {
                    reject("Problem authenticating with LinkedIn");
                }
            }
        });
        browserRef.addEventListener("exit", function (event) {
            reject("The LinkedIn sign in flow was canceled");
        });
    });
}

getLinkedInUserDetails(token: string) {
    let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + token//,
    });
    let options = new RequestOptions({
        headers: headers,
    });
    return this.http.get("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,location,industry,public-profile-url,picture-urls::(original),picture-url,positions,email-address)?format=json", options).toPromise()
   .then(res => res.json(), err => err);
}
1 Like

Thanks a lot! I, however got it working using ng2-cordova-auth (https://github.com/nraboy/ngx-cordova-oauth) and it seemed a lot simpler!

Alguien tuvo éxito con la autenticación de linkedin?

Tuve un verdadero dolor de cabeza con la autenticación de linkedin por medio de OAuth2, estos son los pasos a seguir:

Paso 1: Configure su aplicación:

En la página linkedin developers, crear una nueva aplicación, y tener a la mano el Client ID:, Client Secret: y OAuth 2.0 settings Redirect URLs: es al lugar en donde se redirige nuestro sitio después de hacer las peticiones.

Paso 2: Solicitar un código de autorización:

Debemos realizar una solicitud hacia el API de linkedin como la siguiente, yo arme por medio de un service y haciendo la solicitud por POSTMAN, pero también se puede hacer de otras maneras, lo importante es que la URL de la petición quede de esta manera:

-https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=numero_id_cliente&redirect_uri=URL_para_redireccionar&state=generar_con_letras&scope=r_liteprofile%20r_emailaddress%20w_member_social

Yo lo hice por medio de inAppBrowser, me dirige al inicio de sesión y permisos de linkedin.

Paso 3: Intercambio de código de autorización para un token de acceso:

Una vez que accedes y permites a linkedin, te genera un token de acceso con una duración promedio de 30 minutos, busca la manera en que puedas extraer ese token de acceso porque se utilizará en los siguientes pasos.

ejemplo de la extraccion del token:

this.browser.on(‘loadstart’).subscribe((e) => {

console.log(e.url);
this.url_devuelta = e.url;

if(e.url.match(/^https:\/\/localhost\//)) {
  var miurl = e.url.replace(this.linkedin.redirect_uri+'/?code=', '');
  console.log("token "+(miurl));                            // aquí extraigo el token
  console.log(miurl.length + ' code units long');
  this.autorizaToken(miurl);
  //this.getLinkedInUserDetails(miurl);
 

} else {
  console.log("error "+(this.url_devuelta));
}

});

Paso 4: Hacer solicitudes autenticadas:

Ahora vamos a revalidar el token de la siguiente manera:

https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&redirect_uri=url_redireccion_configurada&client_id=idcliente&client_secret=clientsecretnumber&code=token_generado

Paso 5 Extraer el perfil de usuario:

Con la revalidación del token, ahora debemos enviar una petición con Headers al api de linkedin, lo hice de la siguiente manera:

getLinkedInUserDetails() {

  console.log(this.token_valida);
 console.log("Vivo en la siguiente funcion  "+ this.token_valida);

   let headers = new HttpHeaders().set("Authorization",'Bearer '+ this.token_valida);
   
  

          console.log("Armando los headers "+ 'https://api.linkedin.com/v2/me' + {headers: headers});
          return this.http.get('https://api.linkedin.com/v2/me', {headers: headers}).toPromise()
         .then(res =>
          {
            console.log(res);

         }).catch(error => {
        
          console.log(error);

        
        });
      
      
 }

Esos son los pasos a seguir para la autenticación de linkedin.

Saludos

I wrote a tutorial for implementing LinkedIn OAuth 2.0 in Ionic 4. You can check it out here:

I’ve used the ng2-cordova-oauth plugin and the in app browser plugin to get an access token from LinkedIn. Once that is done, just use the HTTP plugin to query the LinkedIn People REST API