Home > Back-end >  Getting ID from decoded jwt token
Getting ID from decoded jwt token

Time:01-11

I am decoding my token and trying to retreive the userID from the claim I have set in the token. I am trying to get the userID from the token with regex but the response is undefined.

As you can see I am doing the same thing with the token but that is working and I cannot see why it is going wrong with the ID.

onSubmitLogin() {
console.log(this.formLogin.value);

this.userLogin.userEmail = this.formLogin.value.userEmail;
this.userLogin.userPassword = this.formLogin.value.userPassword;

var regextoken = /(?<=value":").*?(?=")/g;
var regexid = /(?<=name": ").*?(?=")/g;

this.userService.login(this.userLogin!).subscribe(
  (data) => {
    var tokenregex = JSON.stringify(data).match(regextoken);
    var token = tokenregex?.[0];
    this.userLogin.token = token!;

    //decode token
    var decodedToken = jwt.decodeToken(token!);
    console.log(decodedToken);
    var idregex = JSON.stringify(decodedToken).match(regexid);
    var id = idregex?.[0];
    //localStorage.setItem('id', id);
    console.log("ID: "   id);
  }
);
}

This is my response in the console: ID: undefined

CodePudding user response:

Remove the space in (?<=name": "):

Try this:

var regexid = /(?<=name":").*?(?=")/g;
  • Related