Simple 2-legged Token Service Sample

Forge Community Blog

Information. Insights. Code. Connections.

Blog
Simple 2-legged Token Service Sample

Simple 2-legged Token Service Sample

April 7, 2017

Some apps that use the Viewer is client side only. However, you still need a read-only token to access the files in your bucket to instantiate the viewer. Do not put your credentials on the front end and use ajax calls. When your credentials are compromised, anyone can access all your files on our servers.

Here is a very simple token service in Node.js that provides a read-only token.

package.json

{
  "name": "autodesk-auth-token",
  "version": "1.0.0",
  "description": "A simple service that serves up a read-only token with Autodesk APIs. This sample retrieves a two-legged token.",
  "main": "index.js",
  "dependencies": {
    "express": "^4.15.2",
    "request": "^2.81.0"
  }
}

index.js

'use strict'

const express = require('express');
const request = require('request').defaults({
  baseUrl: 'https://developer.api.autodesk.com'
});

const app = express();

// put these in environment config
let autodesk_client_id = process.env.autodesk_client_id || '';
let autodesk_client_secret = process.env.autodesk_client_secret || '';
let port = process.env.PORT || 3000;

let expireTime = Date.now();
let token = '';

let options = {
  method: 'POST',
  url: '/authentication/v1/authenticate',
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  },
  form: {
    client_id: autodesk_client_id,
    client_secret: autodesk_client_secret,
    grant_type: 'client_credentials',
    scope: 'data:read'
  }
};

app.get('/', (req, res) => {
  if (!token || Date.now() > expireTime) {
    request(options, (e, r, body) => {
      token = body; // use the entire body as token
      expireTime = Date.now() + JSON.parse(body).expires_in;
      console.log(token);
      res.send(token);
    });
  } else {
    res.send(token);
  }
});

app.listen(port);

To deploy on AWS or heroku, set your process.env.autodesk_client_id and process.env.autodesk_client_secret in the environment variables and it should return a read-only token for you.

Shiya Luo

Shiya is a Developer Evangelist at Autodesk. She creates content around Autodesk's Web Service APIs and the WebGL Viewer. She writes mostly JavaScript now and has spoken at a number of JavaScript/Node.js conferences.