naga-jws
Version:
81 lines (71 loc) • 2.32 kB
JavaScript
const jwt = require('jsonwebtoken');
const axios = require('axios');
const getTBSAccessToken = async (
clientId,
clientSecret,
userToken,
authUrl
) => {
const returnedJws = generateTBSJws(clientId, clientSecret, userToken);
const tbsAuthToken = await fetchAccessToken(returnedJws, authUrl);
return tbsAuthToken;
};
//This function generates the authentication JWS token
const generateTBSJws = (clientId, clientSecret, userToken) => {
//setup the payload with Issuer, Subject, audience and Issued at.
const payload = {
iss: clientId,
sub: clientId,
aud: userToken,
iat: Math.floor(new Date().getTime() / 1000),
};
// Create a new JWS token with the payload
jwsToken = jwt.sign(payload, clientSecret);
return jwsToken;
};
//Fetch the access token by setting the Authentication field in the header.
const fetchAccessToken = async (jwsToken, authUrl) => {
let accessToken = {
token: '',
statusCode: '',
message: '',
};
//axios needs to be setup with the custom header
const options = {
headers: {
Authentication: jwsToken,
},
};
//call the auth url using axios
try {
const res = await axios.get(authUrl, options);
//console.log('res: ', res);
accessToken.token = res.data.AccessToken;
accessToken.statusCode = res.status;
accessToken.message = res.statusText;
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
accessToken.token = null;
accessToken.statusCode = error.response.status;
accessToken.message = error.response.data.Errors;
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log('Request Error', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
// console.log(error.config);
console.log('Complete Error: ', error.toJSON());
}
return accessToken;
};
exports.generateTBSJws = generateTBSJws;
exports.getTBSAccessToken = getTBSAccessToken;