Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'base64url' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
if (transfer.executionCondition === MESSAGE_STRING) {
this._handleLedgerMessage(transfer)
break
}
// check that the incoming transfer is locked with the right control program
await escrow.verify({
utxo: output,
client: this._client,
sourceReceiver: output.referenceData.sourceReceiver,
destinationPubkey: this._key.pubkey,
amount: output.amount,
assetId: output.assetId,
// TODO decide on which part of the codebase is dealing with which date format
expiresAt: moment(output.referenceData.expiresAt).valueOf(),
condition: base64url.decode(output.referenceData.executionCondition, 'hex')
})
// TODO check that all the referenceData we expect is there
debug('emitting incoming_prepare', transfer)
try {
this._safeEmit('incoming_prepare', transfer)
} catch (err) {
console.error('error in event handler', err)
}
} else if (this._outputIsFromUs(output)) {
const transfer = this._parseTransferFromOutput(output)
this._safeEmit('outgoing_prepare', transfer)
}
}
}
console.log('Got access token: %s', access_token);
if (body.refresh_token) {
refresh_token = body.refresh_token;
console.log('Got refresh token: %s', refresh_token);
}
if (body.id_token) {
console.log('Got ID token: %s', body.id_token);
// check the id token
var pubKey = jose.KEYUTIL.getKey(rsaKey);
var signatureValid = jose.jws.JWS.verify(body.id_token, pubKey, ['RS256']);
if (signatureValid) {
console.log('Signature validated.');
var tokenParts = body.id_token.split('.');
var payload = JSON.parse(base64url.decode(tokenParts[1]));
console.log('Payload', payload);
if (payload.iss == 'http://localhost:9001/') {
console.log('issuer OK');
if ((Array.isArray(payload.aud) && _.contains(payload.aud, client.client_id)) ||
payload.aud == client.client_id) {
console.log('Audience OK');
var now = Math.floor(Date.now() / 1000);
if (payload.iat <= now) {
console.log('issued-at OK');
if (payload.exp >= now) {
console.log('expiration OK');
console.log('Token valid!');
export function decodeToken(token: string | TokenInterface): TokenInterface {
if (typeof token === 'string') {
// decompose the token into parts
const tokenParts = token.split('.')
const header = JSON.parse(base64url.decode(tokenParts[0]))
const payload = JSON.parse(base64url.decode(tokenParts[1]))
const signature = tokenParts[2]
// return the token object
return {
header: header,
payload: payload,
signature: signature
}
} else if (typeof token === 'object') {
if (typeof token.payload !== 'string') {
throw new Error('Expected token payload to be a base64 or json string')
}
let payload = token.payload
if (token.payload[0] !== '{') {
payload = base64url.decode(payload)
/****************************************************************************
* JWE compact format structure
****************************************************************************
* BASE64URL(UTF8(JWE Protected Header)) || '.' ||
* BASE64URL(JWE Encrypted Key) || '.' ||
* BASE64URL(JWE Initialization Vector) || '.' ||
* BASE64URL(JWE Ciphertext) || '.' ||
* BASE64URL(JWE Authentication Tag)
***************************************************************************/
var parts = jweString.split('.');
if (parts.length !== 5)
return callback(new Error('In jwe.decrypt: invalid JWE string, it has ' + parts.length + ' parts instead of 5'), null);
var header;
try {
header = JSON.parse(base64url.decode(parts[0], 'binary'));
} catch (ex) {
return callback(new Error('In jwe.decrypt: failed to parse JWE header'), null);
}
var aad = createBuffer(parts[0]);
var encrypted_cek = base64url.toBuffer(parts[1]);
var iv = base64url.toBuffer(parts[2]);
var cipherText = base64url.toBuffer(parts[3]);
var authTag = base64url.toBuffer(parts[4]);
log.info('In jwe.decrypt: the header is ' + JSON.stringify(header));
var cek_result;
var content_result;
// special treatment of 'dir'
let ExtendedJWT = this
let protectedHeader, payload, signature
// Parse
if (typeof data === 'string') {
let segments = data.split('.')
if (![3, 5].includes(segments.length)) {
throw new DataError('Malformed JWT')
}
// Decode base64url
if (segments.length === 3) {
try {
protectedHeader = JSON.parse(base64url.decode(segments[0]))
payload = JSON.parse(base64url.decode(segments[1]))
signature = segments[2]
} catch (err) {
throw new DataError('Malformed JWS')
}
}
if (segments.length === 5) {
// TODO JWE
}
}
// Sanity Check
if (typeof protectedHeader !== 'object' || protectedHeader === null || Array.isArray(protectedHeader)) {
throw new DataError('JWT Header must be an object')
}
***************************************************************************/
var parts = jweString.split('.');
if (parts.length !== 5)
return callback(new Error('In jwe.decrypt: invalid JWE string, it has ' + parts.length + ' parts instead of 5'), null);
var header;
try {
header = JSON.parse(base64url.decode(parts[0], 'binary'));
} catch (ex) {
return callback(new Error('In jwe.decrypt: failed to parse JWE header'), null);
}
var aad = createBuffer(parts[0]);
var encrypted_cek = base64url.toBuffer(parts[1]);
var iv = base64url.toBuffer(parts[2]);
var cipherText = base64url.toBuffer(parts[3]);
var authTag = base64url.toBuffer(parts[4]);
log.info('In jwe.decrypt: the header is ' + JSON.stringify(header));
var cek_result;
var content_result;
// special treatment of 'dir'
if (header.alg === 'dir') {
content_result = decryptContentForDir(header, jweKeyStore, cipherText, iv, authTag, aad, log);
} else {
/****************************************************************************
* cek decryption
***************************************************************************/
var cek_result = decryptCEK(header, encrypted_cek, jweKeyStore, log);
if (cek_result.error)
// read in all the files with secrets, keys, certs
//
var files = {};
switch (config['auth-mode']) {
case 'oauth2':
// look for an oauth secret -- crash if not there
files.oauthSecret = fs.readFileSync(config['oauth-secret'], 'utf8').
replace(/(\n|\r)/gm,''); // newlines can mismatch secret
try { // ok if missing, we will generate
files.sessionSecret = fs.readFileSync(config['session-secret'], 'utf8');
} catch(err) {
console.error('error reading session secret: %s', JSON.stringify(err));
} finally { // just ignore if the file is not there
if (files.sessionSecret == null) {
console.error('generating session secret (will not work with scaled service)');
files.sessionSecret = require('base64url')(require('crypto').randomBytes(256)).substring(0, 256);
}
};
// don't break, do both.
case 'bearer': // and oauth2 as well:
// ensure we validate connections to master w/ master CA.
// technically this might not be required, but passport fails
// silently if it *is* needed and is not present.
var cas = https.globalAgent.options.ca || [];
cas.push(fs.readFileSync(config['master-ca'], 'utf8'));
https.globalAgent.options.ca = cas;
break;
case 'mutual_tls':
try {
files.mutualTlsCa = fs.readFileSync(config['mutual-tls-ca'], 'utf8');
} catch(err) {
throw 'No CA read for mutual TLS. Looked in: ' + config['mutual-tls-ca'];
const batchFileToOperations = batchFile => batchFile.operations.map((op) => {
const decoded = base64url.decode(op);
const decodedOperation = JSON.parse(decoded);
// this was wrong!!!! THE OPERATION HASH IS THE HASH OF THE PAYLOAD
// TODO: use this typescript package instead...
// https://github.com/decentralized-identity/sidetree/blob/361d86b5f10eb8174f4fb5f8871a31384da3e569/lib/core/Operation.ts#L184
const operationHash = base64url.encode(
crypto
.createHash('sha256')
.update(base64url.toBuffer(decodedOperation.payload))
.digest(),
);
return {
operationHash,
decodedOperation,
decodedOperationPayload: JSON.parse(base64url.decode(decodedOperation.payload)),
};
});
selfServiceManager.getForgotPasswordConfirmationResult(context).then(function (result) {
let uuid = result && result.uuid;
if (result && result.success) {
//generate one time code and pass it to the reset password form,
// here we do that in memory but it better to use DB like Redis to do that and store it for temporary time.
let oneTimeCode = base64url.encode(crypto.randomBytes(24));
resetPasswordCodesMap.set(oneTimeCode, {uuid: uuid ,tenantId: tenantId});
logger.debug('rendering ' + resetPasswordFormEjs);
_render(req, res, resetPasswordFormEjs, {uuid: uuid, code: oneTimeCode}, language);
} else {
if (result.error.code === 'NOT_FOUND') {
logger.debug('forgot password result - failure: ' + result.error.description);
_render(req, res, resetPasswordExpiredEjs, {uuid: uuid, errorStatusCode: 'NOT_FOUND', errorDescription: result.error.description}, language);
} else {
logger.error('unexpected forgot password result ' + result);
res.status(500);
res.send('Something went wrong');
}
}
}).catch(function (err) {
logger.error(err);
}).then(function (buf) {
// Base64 the master value for transmission
data.master.value = base64url.encode(buf);
return data;
});
});