Create and rotate an API key with ArcGIS REST JS

ArcGIS REST JSPortalREST APIArcGIS REST JSArcGIS API for Python

Updated Duration: 15 minLevel: Intermediate

What you will build

Two Node.js scripts with ArcGIS REST JS:

  • create-api-key.mjs creates the API key credentials and generates the first key, in slot 1.
  • rotate-api-key.mjs rotates that key without downtime, using the second slot.

Each REST JS function wraps several REST requests; the REST API tutorial shows them one by one.

Check prerequisites

An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account with a Creator user type or higher and the Generate API keys and Assign privileges to OAuth 2.0 applications privileges. Ideally a service user with only those.

Node.js 20.12 or later, for process.loadEnvFile.

Install the packages

Run npm install in the project folder. @esri/arcgis-rest-request signs you in; @esri/arcgis-rest-developer-credentials creates and manages credentials.

Configure the scripts

Copy .env.example to .env and fill it in. .gitignore keeps it out of your repository.

Every request goes to the portal’s https://www.arcgis.com/sharing/rest for ArcGIS Online and ArcGIS Location Platform, https://<host>/<web-adaptor>/sharing/rest for ArcGIS Enterprise.:

The scripts sign in with Backend jobs can’t sign in as you: a username and password don’t work with SAML/SSO or MFA. Create the app credentials in the portal as a service user and assign them that user’s privileges. They are not the client ID and secret of the API key item the script creates., not as you:

Keep the client_secret in a secret manager, and create the app credentials as a service user with only the privileges these scripts need. With admin privileges, the secret can do almost as much damage as your password.

Why the app credentials need their owner’s privileges

Creating and rotating keys with app credentials needs their owner’s user privileges: on ArcGIS Location Platform, createItem, generateApiTokens and assignPrivilegesToApps alone were not enough. The secret can’t sign in or change your password, but it can do whatever those privileges allow.

In production, the same variables can come from the environment or a secret manager instead of .env.

Import the functions

  • ApplicationCredentialsManager: signs in with app credentials.
  • createApiKey: creates the credentials.
  • writeFile: saves the item ID and slot to state.json.

Sign in

process.loadEnvFile() loads .env. ApplicationCredentialsManager gets an app token with the client ID and secret, and renews it when it expires.

Other ways to sign in

To sign in as a user, use ArcGISIdentityManager.beginOAuth2 (OAuth 2.0) or ArcGISIdentityManager.signIn (username and password).

MethodUse it forLimits
Username and passwordTrying things on your machineDoesn’t work with SAML/SSO or MFA accounts; the password ends up in code or the environment.
User authentication (OAuth 2.0)Interactive scripts and appsThe refresh token expires, and changing the password invalidates it.
App credentialsBackend jobs, such as scheduled rotationThey need their owner’s user privileges, and the client_secret can do whatever those privileges allow. Both scripts use them.

Create the credentials

createApiKey takes the same answers as the portal’s wizard. Each comment in the code names the wizard screen the option comes from.

See the privileges reference.

httpReferrers, the sites allowed to use the key, is empty so you can test from scripts or Postman.

Set your app’s URL as a referrer before you ship a public app. Without one, anyone who copies the key can use it from any site, billed to you. You can’t change referrers or the expiration (30 days here) later without invalidating the key.

The four requests behind createApiKey
  1. content/users/{user}/addItem creates the empty item: type=Application, title, tags and the description.
  2. oauth2/registerApp registers it with your privileges and httpReferrers, plus appType=multiple and redirect_uris, which come from OAuth 2.0 credentials: the endpoint requires them, but they don’t affect the key. It returns the client_id and client_secret.
  3. content/users/{user}/items/{id}/update stores apiToken1ExpirationDate in epoch milliseconds. Slot 2 gets -1: no key yet.
  4. oauth2/token generates the key: grant_type=client_credentials, apiToken=1 and regenerateApiToken=true, because generateToken1 is true. On a slot that already holds a key, true replaces it and invalidates the old one at once.

Wizard screens: Item details, Item access, Privileges, Settings, Generate API key.

Save the key

accessToken1 is the key in slot 1. The portal shows it only once: deploy it to your app. state.json keeps the item ID and slot for the rotation script, but not the key.

Where is the client_secret?

createApiKey removes it from the response. The other functions fetch it from registeredAppInfo when they need it.

Rotate: import the functions

  • updateApiKey: generates the key in the new slot.
  • invalidateApiKey: invalidates the old key.
  • readFile, writeFile and createInterface: read and update state.json, and wait while you deploy.

Rotate: start from the key in production

Rotation keeps a valid key at all times: generate a key in the free slot, deploy it, then invalidate the old one.

The script signs in with the same .env and reads the item and current slot from state.json.

Find the free slot

The new key goes into the slot that isn’t in production. Without state.json, slotForKey reads A key ends in AT1_ or AT2_ plus eight characters..

Generate the key in the new slot

updateApiKey sets the new slot’s expiration and generates its key. The key in production keeps working.

Don’t pass privileges or httpReferrers to updateApiKey here. Changing them invalidates the keys of both slots.

REST requests

An item update with the expiration, then oauth2/token with apiToken set to the new slot. Privileges and referrers would go through oauth2/apps/{client_id}/update.

Deploy the new key

Put the new key in production. The old key stays valid until you continue.

Invalidate the old key

invalidateApiKey with the old slot (or old key) invalidates it; passing the new key would invalidate the one you just deployed. The script then saves the new slot to state.json.

REST request

oauth2/revokeToken with the item’s client_id, client_secret and apiToken set to the old slot.

You've completed Create and rotate an API key with ArcGIS REST JS

Next tutorialAuthenticate a Node.js script with ArcGIS REST JS
Download codeAll tutorials Send feedback