const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')
const request = require('request')
const basePath = 'https://identityhomolog.acesso.io'
let options = {
serviceAccount: 'svcapp1',
tenant: "9ea3c3bd-4447-4c3b-ae2e-504b795d3733"
}
requestAnAccessToken(createServiceAccountToken(options), (err, accessToken) => {
let payload = jwt.decode(accessToken.access_token)
console.log('Response:')
console.log(' Access Token: ', accessToken.access_token)
console.log(' ID: ', payload.jti)
console.log(' Issuer: ', payload.iss)
console.log(' Subject: ', payload.sub)
console.log(' expires_in: ', accessToken.expires_in)
console.log(' Expiration Date: ', new Date(payload.exp))
console.log(' Creation Date: ', new Date(payload.iat))
})
function createServiceAccountToken({tenant, serviceAccount, account = ''}) {
let privateKey = fs.readFileSync(path.resolve(`${serviceAccount}.key.pem`))
let payload = {
iss: `${serviceAccount}@${tenant}.iam.acesso.io`,
aud: basePath,
scope: '*',
exp: Math.floor(Date.now() / 1000) + 3600,
iat: Math.floor(Date.now() / 1000)
}
if (account) {
payload.sub = account
}
return jwt.sign(payload, privateKey, { algorithm: 'RS256' })
}
function requestAnAccessToken(serviceToken, callback) {
let options = {
method: 'POST',
url: `${basePath}/oauth2/token`,
headers: {'content-type': 'application/x-www-form-urlencoded'},
form: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer' ,
assertion: serviceToken
}
}
console.log('Requesting Access Token with self created token:' )
console.log('', serviceToken)
request(options, (error, response, body) => {
if (error) {
callback(new Error(error))
}
body = JSON.parse(body)
if (body.error) {
callback(new Error(`${body.error}: ${body.error_description}`))
}
callback(null, body)
})
}