Skip to main content

Exemplo em Javascript

const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')
const request = require('request')

// settings
const basePath = 'https://identityhomolog.acesso.io'

// entry point
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))
})

// functions
function createServiceAccountToken({tenant, serviceAccount, account = ''}) {
// Reads the service account private key
let privateKey = fs.readFileSync(path.resolve(`${serviceAccount}.key.pem`))

// Prepare the request
let payload = {
iss: `${serviceAccount}@${tenant}.iam.acesso.io`,
aud: basePath,
scope: '*',
exp: Math.floor(Date.now() / 1000) + 3600,
iat: Math.floor(Date.now() / 1000)
}
// Service account is requesting an access token for another user?
if (account) {
payload.sub = account
}

// Create JWS
return jwt.sign(payload, privateKey, { algorithm: 'RS256' })
}

function requestAnAccessToken(serviceToken, callback) {
// Prepare the request
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)

// Ask identity and authorization server for an access token
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)
})
}