roemhildtg

ArcGIS Tokens in a Feathers NodeJS App

Blog Post created by roemhildtg on Mar 22, 2018

If you use NodeJS to build apps, you might need a way to connect to map services using ArcGIS server tokens. This example uses feathers and feathers services to accomplish this. Feathers is a service driven NodeJS framework for building restful web apps. This service driven approach allows for a very flexible, and standard way to write API's that allow a client to easily download JSON data.

 

The good stuff: A feathers service for retrieving arcgis tokens:

Check out the full gist here: A NodeJS feathers api for arcgis tokens · GitHub 

const axios = require('axios');
const querystring = require('querystring');

/* eslint-disable no-unused-vars */
class Service {
  constructor (options) {
    this.options = options || {};
  }

  get (id, params) {
    const arcgis = this.options.arcgis;

    // auth data
    const data = {
      f: 'json',
      client: 'referer',
      referer: this.options.host,
      request: 'getToken',
      expiration: arcgis.tokenExpires, // 60 minutes
      username: arcgis.username,
      password: arcgis.password
    };

    // token url
    const url = arcgis.url + '/tokens/generateToken';

    // some headers for passing form data
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'Accept': 'application/json'
    };

    return axios.post(url, querystring.stringify(data), {
      headers
    }).then(result => {
      Object.assign(result.data, {
        server: arcgis.url + '/rest/services',
        ssl: true
      });
      return result.data;
    });
  }
}

module.exports = function (options) {
  return new Service(options);
};

module.exports.Service = Service;

 

Within feathers, access to this service, such as adding authentication, permissions, and other functionality can be controlled using hooks.

 

A Javascript client in a web browser can now access arcgis tokens using this endpoint rather than hitting your arcgis server directly, and your internal arcgis username and passwords are never exposed to the public.

 

require(['esri/identity/IdentityManager'], function(IdentityManager){
    fetch('/api/arcgis-token')
      .then(function(response) {
         identityManager.registerToken(response); //response.json(): {"token":"xyz-token-data","expires":1521755130808,"server":"https://myserver.com/arcgis/rest/services","ssl":true}
      });
});

Outcomes