API key credentials can generate up to two valid API keys at a time, known as AP
and AP
. The keys share identical privileges and item access, but their expiration dates are set individually. By staggering the expiration dates of the two API keys, a single API key credential can be used to run an application indefinitely without downtime.
This tutorial explains how to rotate between an AP
and AP
in a deployed application. You will use arcgis-rest-developer-credentials
module in ArcGIS REST JS to rotate API keys.
Prerequisites
- An ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account. Your account must have a user type of Creator or higher and the correct permissions to generate API keys. To learn more, go to Product and account requirements.
- You need to complete the Create an API key tutorial and generate an
AP
with your desired privileges.I key 1
Steps
Set up the project
This tutorial uses ArcGIS REST JS with Node.js to create a standalone console script. Set up the project directory and install the necessary packages.
-
Create a new directory using a code editor of your choice.
-
Set up a Node JS project and install the following packages using npm or yarn:
@esri/arcgis-rest-developer-credentials
@esri/arcgis-rest-request
dotenv
-
Create a main file called
index.js
. Import methods from ArcGIS REST JS.index.jsUse dark colors for code blocks import { slotForKey, updateApiKey, invalidateApiKey } from "@esri/arcgis-rest-developer-credentials"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request";
Set environment variables
-
Open your project directory in a code editor of your choice.
-
Create a new file named
.env
. -
Add the following lines to your
.env
file and replace the placeholders with your actual credentials:ARCGIS
and_USERNAME ARCGIS
: Your ArcGIS account credentials._PASSWORD PORTAL
(optional): If using ArcGIS Enterprise, update this with your portal's REST endpoint. Otherwise, you can omit this line._URL
.envUse dark colors for code blocks ARCGIS_USERNAME="YOUR_ACCOUNT_USERNAME" ARCGIS_PASSWORD="YOUR_ACCOUNT_PASSWORD" PORTAL_URL="https://{machine.domain.com}/{webadaptor}/sharing/rest" # OPTIONAL - For Enterprise accounts only
-
Find the item ID of your API key credentials. This ID is found in the URL of the item page in your portal, and also returned when creating API keys programmatically with ArcGIS REST JS.
.envUse dark colors for code blocks ARCGIS_USERNAME="YOUR_ACCOUNT_USERNAME" ARCGIS_PASSWORD="YOUR_ACCOUNT_PASSWORD" PORTAL_URL="https://{machine.domain.com}/{webadaptor}/sharing/rest" # OPTIONAL - For Enterprise accounts only API_KEY_ITEM_ID="YOUR_API_KEY_ITEM_ID"
-
Save the file.
Configure authentication
In this step, you will import the necessary classes from the ArcGIS REST JS library and load configuration variables from .env
.
-
Access your environment variables from
.env
by importingdotenv/config
.index.jsUse dark colors for code blocks import { slotForKey, updateApiKey, invalidateApiKey } from "@esri/arcgis-rest-developer-credentials"; import { ArcGISIdentityManager } from "@esri/arcgis-rest-request"; import "dotenv/config";
-
Configure
ArcGIS
with the username, password, and portal URL to set up authentication for the script.Identity Manager Use dark colors for code blocks import "dotenv/config"; const authentication = await ArcGISIdentityManager.signIn({ username: process.env.ARCGIS_USERNAME, password: process.env.ARCGIS_PASSWORD, portal: process.env.PORTAL_URL // OPTIONAL - For ArcGIS Enterprise only });
Generate an API key 2
In this step, you will locate your API key 1 and generate an API key 2 with a new expiration date.
-
Store your current API key in a variable and determine its slot number.
Use dark colors for code blocks let currentApiKey = "YOUR_API_KEY"; const apiKeySlot = slotForKey(currentApiKey);
-
Define an expiration date for the new API key, e.g. three days from now.
Use dark colors for code blocks let currentApiKey = "YOUR_API_KEY"; const apiKeySlot = slotForKey(currentApiKey); const THREE_DAYS = new Date(); THREE_DAYS.setDate(THREE_DAYS.getDate() + 3); THREE_DAYS.setHours(23, 59, 59, 999);
-
Use
update
to create a new API key with the specified expiration date.Api Key Use dark colors for code blocks let currentApiKey = "YOUR_API_KEY"; const apiKeySlot = slotForKey(currentApiKey); const THREE_DAYS = new Date(); THREE_DAYS.setDate(THREE_DAYS.getDate() + 3); THREE_DAYS.setHours(23, 59, 59, 999); const result = await updateApiKey({ itemId: process.env.API_KEY_ITEM_ID, authentication, generateToken1: apiKeySlot === 2, generateToken2: apiKeySlot === 1, apiToken1ExpirationDate: apiKeySlot === 2 ? THREE_DAYS : undefined, apiToken2ExpirationDate: apiKeySlot === 1 ? THREE_DAYS : undefined });
-
Retrieve the newly generated API key and use it to update
current
. Then, print it to the console.Api Key Use dark colors for code blocks let currentApiKey = "YOUR_API_KEY"; const apiKeySlot = slotForKey(currentApiKey); const THREE_DAYS = new Date(); THREE_DAYS.setDate(THREE_DAYS.getDate() + 3); THREE_DAYS.setHours(23, 59, 59, 999); const result = await updateApiKey({ itemId: process.env.API_KEY_ITEM_ID, authentication, generateToken1: apiKeySlot === 2, generateToken2: apiKeySlot === 1, apiToken1ExpirationDate: apiKeySlot === 2 ? THREE_DAYS : undefined, apiToken2ExpirationDate: apiKeySlot === 1 ? THREE_DAYS : undefined }); const newApiKey = apiKeySlot === 2 ? result.accessToken1 : result.accessToken2; currentApiKey = newApiKey; console.log(`\nNew API key in slot ${apiKeySlot === 1 ? 2 : 1} created: ${newApiKey}`);
Deploy your application
After generating an AP
and pasting it into your application, your AP
can be safely deleted from the code base. You must deploy your application to production before the AP
can be invalidated.
-
Deploy your application to production using your normal process. This process varies based on your chosen platform, programming language, and build system.
Invalidate the API key 1
After your application has been deployed with a new API key, the previous API key is no longer required. Invalidate the key to prevent fraudulent usage.
- Call
invalidate
to revoke the previous API key. If the operation is successful, log the result to confirm the key has been invalidated.Api Key Use dark colors for code blocks const invalidateResponse = await invalidateApiKey({ itemId: process.env.API_KEY_ITEM_ID, authentication, apiKey: currentApiKey }); if (invalidateResponse.success) { console.log(`\nOld key in slot ${apiKeySlot} invalidated.`); }