Last active
April 20, 2020 20:46
-
-
Save wallabyway/076fa7057deed8c0af839a708b0b5340 to your computer and use it in GitHub Desktop.
Nodejs - Refresh token (generate a 3-legged AccessToken) for Robot accounts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To install: > npm install node-fetch node-persist | |
// Notes: node-persist stores the refresh token data, into a text file on disk, so | |
// if the server reboots, the refresh token is persisted. | |
const fetch = require('node-fetch'); | |
const storage = require('node-persist'); | |
const FORGEURL = `https://developer.api.autodesk.com`; | |
// This mechanism provides an Access Token to BIM360 APIs, as a standard user, not 2-legged. | |
// It does this by using a 3-legged refreshToken to automatically generate a new AccessToken. | |
class RefreshMechanism { | |
constructor() { | |
this.newRefreshToken(); | |
setInterval(i => this.newRefreshToken(), (3600*1000)); //get new access token every hour | |
} | |
async newRefreshToken() { | |
await storage.init(); //init node-persist | |
this.FORGE_KEY = `<enter your forge-key here>`; | |
this.FORGE_SECRET = `<enter your forge-secret here>`; | |
let refreshToken = await storage.getItem('refreshToken'); // get our last refresh token | |
fetch(`${FORGEURL}/authentication/v1/refreshtoken`, { | |
method: 'POST', | |
body: `client_id=${this.FORGE_KEY}&client_secret=${this.FORGE_SECRET}&grant_type=refresh_token&refresh_token=${refreshToken}`, | |
headers: { "Content-Type": 'application/x-www-form-urlencoded' }, | |
}) | |
.then(res => res.json()) | |
.then(res => { | |
this.access_token = res.access_token; | |
this.refresh_token = res.refresh_token; | |
if (this.refresh_token) | |
storage.setItem('refreshToken',this.refresh_token); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment