How to get Token from JWT


#1

I am trying to get the uncoded token from a ws, but I do not succeed. The token is JWT. The token that the ws returns to me is the following:

{\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDb2RpZ28iOiIxMTY4IiwiVXN1YXJpbyI6IjU0MDMyIiwiUGFzc3dvcmQiOiJmZGM3OTZlNzkwMjk2NTdjZGE2YjY1OWQ3NjI0MjAyYSIsIk5vbWJyZXMiOiJEYW5pbG8gRXN0dWFyZG8iLCJBcGVsbGlkb3MiOiJJdHplcCBMdW5hIiwiTm9tYnJlQ29tcGxldG8iOiJEYW5pbG8gRXN0dWFyZG8gSXR6ZXAgTHVuYSIsIlRva2VuIjoiNzQ1QzMzNjktMUUwMy00QTJBLTk1Q0YtMzI4NTZGRUU0MEQ2Iiwic3RhdHVzIjoiT0siLCJuYmYiOjE1NDE0NDkzOTcsImV4cCI6MTU0MTQ1MTE5NywiaWF0IjoxNTQxNDQ5Mzk3LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ5OTc1LyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDk5NzUvIn0.aZA9yOosJzQqZdpMkYtzIHOj3oqYv5tU_qffVyIXOkg\"}

I only need the following code, without diagonals:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDb2RpZ28iOiIxMTY4IiwiVXN1YXJpbyI6IjU0MDMyIiwiUGFzc3dvcmQiOiJmZGM3OTZlNzkwMjk2NTdjZGE2YjY1OWQ3NjI0MjAyYSIsIk5vbWJyZXMiOiJEYW5pbG8gRXN0dWFyZG8iLCJBcGVsbGlkb3MiOiJJdHplcCBMdW5hIiwiTm9tYnJlQ29tcGxldG8iOiJEYW5pbG8gRXN0dWFyZG8gSXR6ZXAgTHVuYSIsIlRva2VuIjoiNzQ1QzMzNjktMUUwMy00QTJBLTk1Q0YtMzI4NTZGRUU0MEQ2Iiwic3RhdHVzIjoiT0siLCJuYmYiOjE1NDE0NDkzOTcsImV4cCI6MTU0MTQ1MTE5NywiaWF0IjoxNTQxNDQ5Mzk3LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ5OTc1LyIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDk5NzUvIn0.aZA9yOosJzQqZdpMkYtzIHOj3oqYv5tU_qffVyIXOkg

This is the function that the token obtains:

doLogin() {
    const body = {
      Codigo: "1168",
      Usuario: "54032",
      Password: "01992004"
    };
    this.webService.doLogin(body)
    .then((response) => {

      this.jsonToken = response.data;

      this.nativeStorage.set("json", this.jsonToken);
      this.toasNative.show(this.jsonToken, "3000", "bottom").subscribe();
      
      this.navCtrl.push(HomePage);
    }).catch((error) => {
      this.toasNative.show(error, "3000", "bottom").subscribe();
    });
  }

This is the component:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HomePage } from '../home/home';

import { Storage } from '@ionic/storage';

import { ServiceProvider } from '../../providers/service/service';

import { Toast } from '@ionic-native/toast';
import * as jwt_decode from "jwt-decode";

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  paginaprincipal: any = HomePage;
  loading: any;
  jsonToken: any;
  
  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    private webService: ServiceProvider,
    private nativeStorage: Storage,
    private toasNative: Toast) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  doLogin() {
    const body = {
      Codigo: "1168",
      Usuario: "54032",
      Password: "01992004"
    };
    this.webService.doLogin(body)
    .then((response) => {

      this.jsonToken = JSON.stringify(response.data);

      this.nativeStorage.set("json", this.jsonToken);
      this.toasNative.show(this.jsonToken, "3000", "bottom").subscribe();
      
      this.navCtrl.push(HomePage);
    }).catch((error) => {
      this.toasNative.show(error, "3000", "bottom").subscribe();
    });
  }
}

The provider is the following:

doLogin(arrayData) {
    return this.nativeHttp.post(this.url + '/api/Login', arrayData, {
      "Content-Type": this.header1,
    });
  }

I tried parsing the token, but when I want to get the value I get an error that item 0 does not exist.

this.jsonToken = JSON.parse(response.data);

Or

this.jsonToken = JSON.stringify(response.data);

And

this.jsonToken[‘token’]

Can you please help me get the token? Thank you.


#2

Answer here?

function parseJwt (token) {
            var base64Url = token.split('.')[1];
            var base64 = base64Url.replace('-', '+').replace('_', '/');
            return JSON.parse(window.atob(base64));
        };

The Stack Overflow answer is located here:


#3

I tried but it did not work. Thanks.


#4

greetings,
I leave you below as I do in my application, this is working since I have a business apk working with this:

import CryptoJS from ‘crypto-js’;
GenerarToken(data)
{
let datos:string = btoa(JSON.stringify(data));
let encabezado:string = btoa(JSON.stringify({
“typ”: “JWT”,
“alg”: “HS256”
}));
let unido:string = encabezado + “.” + datos;
var llave = CryptoJS.HmacSHA256(unido, key);
var signature = llave.toString(CryptoJS.enc.Base64);
let token = unido + ‘.’ + signature;
return token;
}
GenerarHeader(data)
{
let datos:string = btoa(JSON.stringify(data));

let encabezado:string = btoa(JSON.stringify({
  "typ": "JWT",
  "alg": "HS256"
}));

let unido:string = encabezado +  "." + datos;
var llave = CryptoJS.HmacSHA256(unido, key);
var signature = llave.toString(CryptoJS.enc.Base64);
let token = unido + '.' + signature;

return token; 

}

and to rescue the token that returns the service I do it in the following way:

import * as JWT from ‘jwt-decode’;
ionViewDidEnter()
{
this.platform.ready().then(() => {
this.loading = this.loadingController.create({ content: “cargando…” });
this.loading.present();
this.kiberKiberpro.CargaLiquidaciones(this.rutUsuario).then((res) => {
this.resultado = res;
var respuesta = JSON.parse(this.resultado.data);
var data = JWT(respuesta.data);
if(respuesta.status == “200”){
if(data == null){
this.alerta(“user does not have documents.”);
this.loading.dismissAll();
this.navCtrl.setRoot(HomePage);
}
else
{
this.liquidaciones = data;
this.loading.dismissAll();
}
}
else if (respuesta.status == “401”){
this.alerta(“your session has expired.”);
this.loading.dismissAll();
this.navCtrl.setRoot(LoginPage);
}
else{
this.alerta(“any error”);
this.loading.dismissAll();
}
}, (err) => {
this.alerta(“Any error”);
this.loading.dismissAll();
});
});
}

hope it serves you and any questions I remain attentive to your comments.