Get Token-Jwt on Ionic

0

I am consuming an ApiRest in which I get a Token Jwt. The problem I have is that for example the token I receive comes in the following way:

Code:

let jwt = jwt_decode(resp);

Token Obtained:

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDb2RpZ28iOiI1NDAzMiIsIlVzdWFyaW8iOiJEYW5pbG8iLCJQYXNzd29yZCI6IjNkYzlkNDZhN2NhZThhYzQ3MTU1NjE4ZDZhYmZkZjdlIiwiTm9tYnJlcyI6IkRhbmlsbyIsIkFwZWxsaWRvcyI6Ikl0emVwIiwiTm9tYnJlQ29tcGxldG8iOiJEYW5pbG8gSXR6ZXAiLCJUb2tlbiI6IjEyMzQ1Iiwic3RhdHVzIjoiT0siLCJuYmYiOjE1Mzk2NjEzMzIsImV4cCI6MTUzOTY2MzEzMiwiaWF0IjoxNTM5NjYxMzMyLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ5ODYvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0OTg2LyJ9.VoUVi5Pjj03SMZTOlN3i95tP45QGtyJ_Se8s6pKzPwI"}

And what I need is only:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDb2RpZ28iOiI1NDAzMiIsIlVzdWFyaW8iOiJEYW5pbG8iLCJQYXNzd29yZCI6IjNkYzlkNDZhN2NhZThhYzQ3MTU1NjE4ZDZhYmZkZjdlIiwiTm9tYnJlcyI6IkRhbmlsbyIsIkFwZWxsaWRvcyI6Ikl0emVwIiwiTm9tYnJlQ29tcGxldG8iOiJEYW5pbG8gSXR6ZXAiLCJUb2tlbiI6IjEyMzQ1Iiwic3RhdHVzIjoiT0siLCJuYmYiOjE1Mzk2NjEzMzIsImV4cCI6MTUzOTY2MzEzMiwiaWF0IjoxNTM5NjYxMzMyLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ5ODYvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0OTg2LyJ9.VoUVi5Pjj03SMZTOlN3i95tP45QGtyJ_Se8s6pKzPwI

Without being enclosed in {"token": ""}

For this reason, try to obtain the code in several ways, but without achieving it.

If I only save it as an object:

[object Object]: {Apellidos: "Itzep", aud: "http://localhost:4986/", Codigo: "54032", exp: 1539663477, iat: 1539661677...}
Apellidos: "Itzep"
aud: "http://localhost:4986/"
Codigo: "54032"
exp: 1539663477
iat: 1539661677
iss: "http://localhost:4986/"
nbf: 1539661677
NombreCompleto: "Danilo Itzep"
Nombres: "Danilo"
Password: "3dc9d46a7cae8ac47155618d6abfdf7e"
status: "OK"
Token: "12345"
Usuario: "Danilo"
__proto__: Object

If I convert it to json, I get the following:

{"Codigo":"54032","Usuario":"Danilo","Password":"3dc9d46a7cae8ac47155618d6abfdf7e","Nombres":"Danilo","Apellidos":"Itzep","NombreCompleto":"Danilo Itzep","Token":"12345","status":"OK","nbf":1539661677,"exp":1539663477,"iat":1539661677,"iss":"http://localhost:4986/","aud":"http://localhost:4986/"}

The code is as follows:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AlertController, Platform } from "ionic-angular";
import 'rxjs/add/operator/map';
import * as jwt_decode from "jwt-decode";
import { URLSearchParams } from '@angular/http';
import { HttpHeaders } from '@angular/common/http';
import { Storage } from '@ionic/storage';

@Injectable()
export class ServiceRestProvider {

  Token: any;
  token_full: any;
  jwt_token: any;
  token_full_json: any;

  constructor(public http: HttpClient,
    private alertCtrl: AlertController,
    private platform: Platform,
    private storage: Storage) {

    console.log('Entrando a ServiceRestProvider Provider y cargar storage');

    this.cargar_storage();
  }

  activo(): boolean {

    if (this.Token != "") {
      console.log("true");
      return true;

    } else {
      console.log("false");
      return false;
    }
  }

  ingresar(codigo: string, usuario: string, contrasena: string) {

    const body = JSON.stringify({
      Codigo: codigo,
      Usuario: usuario,
      Password: contrasena
    });

    const headers = new HttpHeaders().set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
      .set('Accept', 'application/json')
      .set('Content-Type', 'application/json; charset=utf-8');

    return this.http.post('api/Api/Login', body, { headers: headers })
      .map((resp: any) => {

        let jwt = jwt_decode(resp);

        console.log("Pruebas");
        console.log(jwt);

        console.log("resp sin formato");
        console.log(resp);

        console.log("resp decodificado con jwt");
        this.token_full = jwt_decode(resp);
        console.log(this.token_full);

        console.log("resp con json");
        console.log(JSON.stringify(jwt));

        if (resp.error) {
          this.alertCtrl.create({
            title: "Error al iniciar",
            subTitle: jwt['Apellidos'],
            buttons: ["OK"]
          }).present();
        } else {
          console.log("No hubo error al cargar");
          this.Token = jwt['Token'];
          this.token_full=resp;
          console.log(this.Token + this.token_full);
          this.guardar_storage();
        }
      }
      );
  }

  private guardar_storage() {
    if (this.platform.is("cordova")) {
      console.log("El token a guardar en storage es");
      console.log(this.Token);
      this.storage.set('Token', this.Token);
      this.storage.set('Token_Full', this.token_full);

    } else {
      if (this.Token != "") {
        console.log("Guardando token");
        localStorage.setItem("Token", this.Token);
        localStorage.setItem("Token_Full", this.token_full);
        console.log("El token guardado es:");
        console.log(localStorage.getItem("Token_Full"));
      } else {
        console.log("Removiendo token del local storage");
        localStorage.removeItem("Token");
        localStorage.removeItem("Token_Full");
      }
    }
  }

  cargar_storage() {
    console.log("Entrando a cargar local storage");
    let promesa = new Promise((resolve, reject) => {

      if (this.platform.is("cordova")) {
        // dispositivo
        console.log("Existen items en el local storage dispositivo cordova");
        this.storage.ready()
          .then(() => {

            this.storage.get("Token_Full")
              .then(Token => {
                console.log(Token);
                if (Token != "") {
                  this.Token = Token;
                  this.token_full=Token;
                }
              })
          })
      } else {
        // computadora
        if (localStorage.getItem("Token_Full")) {
          //Existe items en el localstorage
          console.log("Existen items en el local storage computadora");
          this.token_full = localStorage.getItem("Token_Full");
          console.log(localStorage.getItem("Token_Full"));
        }
        resolve();
      }
    });
    return promesa;
  }

  getNovedades() {
    console.log("Token en almacenamiento interno");
    console.log(localStorage.getItem("Token_Full"));

    return new Promise(resolve => {
      this.http.post('api/Api/Licencias','12122017/12122018',{
        headers: new HttpHeaders().set('Authorization', localStorage.getItem("Token_Full")),
      }).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }

  Cerrar_Sesion() {

    this.token_full = null;
    // guardar storage
    this.guardar_storage();
  }
}

If you can help me get the token without the tag, I appreciate it. Greetings.

    
asked by raintrooper 16.10.2018 в 06:05
source

2 answers

1

Get the token as follows:

let jwt_json1 = JSON.parse(resp);
console.log(jwt_json1["token"]);
    
answered by 16.10.2018 в 15:42
0

You can call a token as a property of your object, in the following way:

const response_token ={"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJDb2RpZ28iOiI1NDAzMiIsIlVzdWFyaW8iOiJEYW5pbG8iLCJQYXNzd29yZCI6IjNkYzlkNDZhN2NhZThhYzQ3MTU1NjE4ZDZhYmZkZjdlIiwiTm9tYnJlcyI6IkRhbmlsbyIsIkFwZWxsaWRvcyI6Ikl0emVwIiwiTm9tYnJlQ29tcGxldG8iOiJEYW5pbG8gSXR6ZXAiLCJUb2tlbiI6IjEyMzQ1Iiwic3RhdHVzIjoiT0siLCJuYmYiOjE1Mzk2NjEzMzIsImV4cCI6MTUzOTY2MzEzMiwiaWF0IjoxNTM5NjYxMzMyLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjQ5ODYvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0OTg2LyJ9.VoUVi5Pjj03SMZTOlN3i95tP45QGtyJ_Se8s6pKzPwI"}
console.log(response_token.token)
    
answered by 16.11.2018 в 23:14