I am trying to get value of a token but I get error ERROR TypeError: Cannot read property 'token' of undefined
code
//Below code gives the output shown below with black color text
data.text()
// I am interested in fetching token value which is nested inside success keyword, below code fails to get the token
var abc = data.text();
abc['success'].token
let abc = JSON.parse(data.text());
var abc = (JSON.parse(data._body)).success.token;
Following code is for reading JWT form js
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
};
How to decode jwt token in javascript
Related
So I want to print out the client Name and the client Email as string values through the Postman console, but when I call the method I get a the array but with undefined values.
const res = pm.response.json();
const req = pm.request.toJSON();
let user = [req.body.raw.clientName, req.body.raw.clientName];
console.log(user);
Thank you very much!
You can get request body raw using:
pm.request.body.raw
For example:
You have request body in postman:
{
"foo": "bar"
}
You want to access value of foo in tab Tests:
const req = JSON.parse(pm.request.body.raw)
console.log(req.foo);
I am implementing FIDO2(WebAuthn) in a Angular application.
I have gotten the PublicKeyCredentialCreationOptions object and seccessfullt register.
But after calling
let response = await navigator.credentials.create({'publicKey': myPublicKeyCredentialCreationOption })
I try to send the response to the server.. But this fails.
When I tried to look at the object in the browser using
console.log(JSON.stringify(response))
I get
{}
as output (?..) but when doing
console.log(response)
I get a object with values in the console...
How should the object get serialized to send to the server?
PublicKeyCredential objects contains ArrayBuffer objects that cannot be serialized as JSON. You could base64 encode these values in your Angular app and decode on the server to get the same byte array back. A helper library to do exactly that for WebAuthn exists: https://github.com/github/webauthn-json
Here's a very simple example for anyone who needs it:
function bufferToBase64url (buffer) {
// modified from https://github.com/github/webauthn-json/blob/main/src/webauthn-json/base64url.ts
const byteView = new Uint8Array(buffer);
let str = "";
for (const charCode of byteView) {
str += String.fromCharCode(charCode);
}
// Binary string to base64
const base64String = btoa(str);
// Base64 to base64url
// We assume that the base64url string is well-formed.
const base64urlString = base64String.replace(/\+/g, "-").replace(
/\//g,
"_",
).replace(/=/g, "");
return base64urlString;
}
...
create publicKeyCredentialCreationOptions
...
navigator.credentials.create({
publicKey: publicKeyCredentialCreationOptions
}).then(credential => {
// credential created
// console.log(credential); <-- check what is output to see what you need to call bufferToBase64url(credential.<...>) on down below
// convert credential to json serializeable
const serializeable = {
authenticatorAttachment: credential.authenticatorAttachment,
id: credential.id,
rawId: bufferToBase64url(credential.rawId),
response: {
attestationObject: bufferToBase64url(credential.response.attestationObject),
clientDataJSON: bufferToBase64url(credential.response.clientDataJSON)
},
type: credential.type
};
const serialized = JSON.stringify(serializeable);
console.log(serialized);
}).catch(err => {
// an error occurred
console.error(err);
});
I have encrypt my token and data json object like this and that's redirect to a subdomain web app with a guard angular :
// access website Wordpress/jQuery/Crypto-js 3.1.9-1
let encrypted = CryptoJS.AES.encrypt(JSON.stringify(response), SECRET_PASSPHRASE);
window.location.href = APP_HOME + "?access=" + encrypted;
The redirection work's as well but I have this error when my guard try to deycrpt the "access" param.
Error: Malformed UTF-8 data
at Object.stringify (core.js:478)
at WordArray.init.toString (core.js:215)
at AuthGuard.push../src/app/_guards/auth/auth.guard.ts.AuthGuard.decryptData (auth.guard.ts:62)
at AuthGuard.push../src/app/_guards/auth/auth.guard.ts.AuthGuard.canActivate
My function to decrypt - Angular WebApp - I try a lot of variations because I find a lot of persons to have the same bug with this error "Malformed UTF-8 data'.
/* Angular - Crypto-js 3.1.9-1 */
import * as CryptoJS from 'crypto-js';
...
decryptData(data) {
try {
const bytes = CryptoJS.AES.decrypt(data.toString(), this.encryptSecretKey);
let decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
//let aa = CryptoJS.enc.Utf8.stringify(bytes)
// let aa = bytes.toString(CryptoJS.enc.Utf8);
console.log('decryptedData ==>', decryptedData);
return JSON.stringify(decryptedData);
} catch (e) {
console.log(e);
}
}
I am trying to do a weather underground query by creating jsonp. In their official documents it says that cb is the callback name (https://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1#using_results), however, I keep getting an "Uncaught SyntaxError: Unexpected token :" error. I'm trying to do this in pure javascript but I am having no such luck and all of the examples that I have found are jquery methods. Any help would be appreciated.
This is an example of the error: "Uncaught SyntaxError: Unexpected token : aq?query=Sacramento?callback=cb:1"
Here is the javascript code:
var citySearch = document.getElementById("citySearchForm");
var search;
function searchFormFunc(e){
jsonP = "?callback=cb";
cityName = document.getElementById('getCitiesInput').value;
var cityNameJsonP = cityName + jsonP;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
search = searchCityLink.concat(cityNameJsonP);
console.log(search);
var script = document.createElement('script');
script.src = search;
document.getElementsByTagName('head')[0].appendChild(script);
function cb(data){
console.log("fired");
console.log(data);
}
}
Your URL is going to be
http://autocomplete.wunderground.com/aq?query=FOOBAR?callback=cb
a valid url via their api would be
http://autocomplete.wunderground.com/aq?query=20500&cb=cb
You should be encoding the value and you should be using & for multiple querystring parameters.
jsonP = "&cb=cb";
cityName = encodeURICompontent(document.getElementById('getCitiesInput').value);
var cityNameJsonP = cityName + jsonP;
I'm creating my first ever login system, using JsonWebTokens, and I've hit an obstacle trying to use the encode function.
My error message says:
if (this.ended && !this.hasRejectListeners()) throw reason;
^ TypeError: undefined is not a function
and I've managed to narrow the error down to this line of code:
var jwt = require('jsonwebtoken');
jwt.encode(payload, superSecret);
The function this is a part of looks like this:
var moment = require('moment');
var jwt = require('jsonwebtoken');
var superSecret = require('../config/token.js').secret;
function (user) {
var payload = {
sub: user._id,
iat: moment().unix(),
exp: moment().add(14, 'days').unix()
};
return = jwt.encode(payload, superSecret);
Needless to say, since this is the first time I'm authenticating anything, I don't know why this would cause an error. Please help.