Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function generateToken(schema, userId, collectionId, periodId = '201605', periodStr = 'May 2016', regionCode = 'GB-ENG', languageCode = 'en', sexualIdentity = false, includeLogoutUrl = true) {
let schemaParts = schemaRegEx.exec(schema);
// Header
let oHeader = {
alg: 'RS256',
typ: 'JWT',
kid: '709eb42cfee5570058ce0711f730bfbb7d4c8ade'
};
// Payload
let oPayload = {
tx_id: uuid(),
jti: uuid(),
iat: KJUR.jws.IntDate.get('now'),
exp: KJUR.jws.IntDate.get('now') + 1800,
user_id: userId,
case_id: uuid(),
ru_ref: '12346789012A',
ru_name: 'Apple',
trad_as: 'Apple',
eq_id: schemaParts[1],
collection_exercise_sid: collectionId,
period_id: periodId,
period_str: periodStr,
ref_p_start_date: '2017-01-01',
ref_p_end_date: '2017-02-01',
employment_date: '2016-06-10',
form_type: schemaParts[2],
return_by: '2017-03-01',
region_code: regionCode,
if (tokRes.statusCode >= 200 && tokRes.statusCode < 300) {
var body = JSON.parse(tokRes.getBody());
access_token = body.access_token;
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) {
// not in the header, check in the form body
inToken = req.body.access_token;
} else if (req.query && req.query.access_token) {
inToken = req.query.access_token
}
console.log('Incoming token: %s', inToken);
var tokenParts = inToken.split('.');
var header = JSON.parse(base64url.decode(tokenParts[0]));
var payload = JSON.parse(base64url.decode(tokenParts[1]));
console.log('Payload', payload);
var publicKey = jose.KEYUTIL.getKey(rsaKey);
if (jose.jws.JWS.verify(inToken,
publicKey,
[header.alg])) {
console.log('Signature validated');
if (payload.iss == 'http://localhost:9001/') {
console.log('issuer OK');
if ((Array.isArray(payload.aud) && __.contains(payload.aud, 'http://localhost:9002/')) ||
payload.aud == 'http://localhost:9002/') {
console.log('Audience OK');
var now = Math.floor(Date.now() / 1000);
if (payload.iat <= now) {
console.log('issued-at OK');
if (payload.exp >= now) {
if (code) {
delete codes[req.body.code]; // burn our code, it's been used
if (code.request.client_id == clientId) {
//var access_token = randomstring.generate();
var header = { 'typ': 'JWT', 'alg': 'HS256' };
var payload = {
iss: 'http://localhost:9001/',
sub: code.user ? code.user.sub : undefined,
aud: 'http://localhost:9002/',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (5 * 60),
jti: randomstring.generate(8)
};
var access_token = jose.jws.JWS.sign(header.alg,
JSON.stringify(header),
JSON.stringify(payload),
new Buffer(sharedTokenSecret).toString('hex'));
nosql.insert({ access_token: access_token, client_id: clientId, scope: code.scope, user: code.user });
console.log('Issuing access token %s', access_token);
var token_response = { access_token: access_token, token_type: 'Bearer', scope: code.scope.join(' ') };
res.status(200).json(token_response);
console.log('Issued tokens for code %s', req.body.code);
return;
} else {
console.log('Client mismatch, expected %s got %s', code.request.client_id, clientId);
async createJwt(){
var pubKey = this.state.keypair.pubKeyObj;
const jwkPrv2 = KEYUTIL.getJWKFromKey(this.state.keypair.prvKeyObj);
const jwkPub2 = KEYUTIL.getJWKFromKey(this.state.keypair.pubKeyObj);
console.log(pubKey);
const currentTime = KJUR.jws.IntDate.get('now');
const endTime = KJUR.jws.IntDate.get('now + 1day');
const kid = KJUR.jws.JWS.getJWKthumbprint(jwkPub2)
// const pubPem = {"pem":KEYUTIL.getPEM(pubKey),"id":kid};
const pubPem = {"pem":jwkPub2,"id":kid};
// Check if the public key is already in the db
const checkForPublic = await fetch("http://localhost:3001/public_keys?id="+kid,{
"headers":{
"Content-Type":"application/json"
},
"method":"GET"
}).then(response => {return response.json()});
if(!checkForPublic.length){
// POST key to db if it's not already there
const alag = await fetch("http://localhost:3001/public_keys",{
"body": JSON.stringify(pubPem),
function generateJWT(audience) {
const jwtPayload = JSON.stringify({
iss: 'https://sandbox.cds-hooks.org',
aud: audience,
exp: Math.round((Date.now() / 1000) + 3600),
iat: Math.round((Date.now() / 1000)),
jti: uuid(),
});
const jwtHeader = JSON.stringify({
alg: 'ES256',
typ: 'JWT',
kid: 'd9cd3c4f-eb08-4304-b973-44f352fd2ca2',
});
return JWT.jws.JWS.sign(null, jwtHeader, jwtPayload, privKey);
}
}
const header = {
"alg":"RS256",
"typ":"JWT",
"kid":kid,
"jku":"http://localhost:3001/public_keys"
};
const body = {
"iss":"localhost:3000",
"aud":"r4/order-review-services",
"iat": currentTime,
"exp": endTime,
"jti": this.makeid()
}
var sJWT = KJUR.jws.JWS.sign("RS256",JSON.stringify(header),JSON.stringify(body),jwkPrv2)
return sJWT;
}
var debug = require('debug')('plugin:oauth');
var url = require('url');
var rs = require('jsrsasign');
var fs = require('fs');
var path = require('path');
const memoredpath = '../third_party/memored/index';
var sharedMemoryCache = require(memoredpath);
//creating aliases for apiKeyCache and validTokenCache for readability
//both the apiKeyCache and the validTokenCache point to the same
//instance of shared memory cache
const apiKeyCache = sharedMemoryCache;
const validTokenCache = sharedMemoryCache;
var JWS = rs.jws.JWS;
var requestLib = require('request');
var _ = require('lodash');
const authHeaderRegex = /Bearer (.+)/;
const PRIVATE_JWT_VALUES = ['application_name', 'client_id', 'api_product_list', 'iat', 'exp'];
const SUPPORTED_SINGLE_FORWARD_SLASH_PATTERN = "/";
const LOG_TAG_COMP = 'oauth';
const acceptAlg = ['RS256'];
var acceptField = {};
acceptField.alg = acceptAlg;
var productOnly;
var cacheKey = false;
}
let expire = moment.utc().add(1, 'minutes').unix();
let md = forge.md.sha256.create();
md.update(method + uri + body);
var oHeader = {alg: 'RS512', typ: 'JWT'};
var oPayload = {
uid: uid,
sid: sid,
exp: expire,
jti: uuid(),
sig: md.digest().toHex()
};
var sHeader = JSON.stringify(oHeader);
var sPayload = JSON.stringify(oPayload);
return KJUR.jws.JWS.sign('RS512', sHeader, sPayload, privateKey);
},
function buildJwt(hookUrl, data) {
var payload = JSON.stringify({
iss: `${window.location.protocol}//legacy-sandbox.cds-hooks.org`,
aud: hookUrl,
exp: Math.round((Date.now() / 1000) + 3600),
iat: Math.round((Date.now() / 1000)),
jti: uuidv4(),
});
var header = JSON.stringify({
alg: 'ES256',
typ: 'JWT',
kid: '9b4f5be8-055a-408d-9e1a-1af98dcf2509',
});
return JWT.jws.JWS.sign(null, header, payload, data);
}