# Developer Credentials Manager Demo

> Sign in, manage groups and turn API keys into organized content with ArcGIS REST JS, step by step.

Interactive version: http://www.rauljimenez.info/arcgis-tutorials/credential-console-basics/

## About this demo

You will build the basics of **Credential Console**: a browser app to organize API keys by customer, using only ArcGIS REST JS.

The use case is fictional. **GeoDataProvider GmbH** sells urban data hosted on **[ArcGIS Location Platform](https://location.arcgis.com/)** to customers who don't use ArcGIS (a city, a property portal, a micromobility startup on a trial…). They use that data in their own apps, and each customer app gets **API keys** scoped to the layers it paid for.

With a handful of keys this is doable. With dozens, the provider needs answers that span many credentials: what expires this month, what each key has access to, which keys belong to which customer.

![need.svg](http://www.rauljimenez.info/arcgis-tutorials/_astro/need.BEjZ8Ved.svg)

## What ArcGIS gives you today

You can already manage all of this through different ArcGIS tools and interfaces:

1. **Portal > My content** lists and filters credentials, and lets you create them.
1. **ArcGIS Location Platform** adds an enhanced search experience and more credential info, like usage reports.
1. The **item page overview** of a credential lets you edit its metadata and tags, shows the privileges of the API key, and lets you share it with groups.
1. The **item page settings** of a credential let you:
    1. Edit its privileges: ArcGIS services and item access.
    1. Manage its two API keys (shown partially) and its referrers.
1. **Portal > Groups** lists, searches and filters your groups, and lets you create new ones.
1. The **group page** lets you edit the group's details and shows the items shared with it.

But every organization works in its own way (by customer, by team, by contract), and no general-purpose UI can fit every workflow perfectly. Because everything is available through the ArcGIS REST APIs, you can build a UI that fits yours.

[Embedded page](https://docs.google.com/presentation/d/e/2PACX-1vT-K2Pn0xJjGyDoewbDIcZ8-HQ9ecWj3BdmnKMual3vXT0D0GEHMwIlT3x0rc8ZBSZVzAOW_p4W__Oc/pubembed?start=false&loop=false&delayms=3000)

## The end goal

This is the dashboard GeoDataProvider is looking for: one place to organize credentials by customer, audit them and rotate API keys, with **fewer pages and far fewer clicks**.

It is built only with ArcGIS REST JS in the browser. Try it: it runs here with fictional data.

- Projects on the left are ArcGIS **groups**.
- Each credential is an ArcGIS **item**, shared with its project and carefully tagged.

<details>
<summary>What does it add to what ArcGIS gives you today?</summary>

- **Situation overview**: API keys, OAuth apps, tokens expiring soon and critical issues.
- **Advanced search**: by customer name, tag, client ID, partial key…
- **Needs triage**: credentials not assigned to any project yet.
- **Tags grouped by family** in the UI.
- **Items assigned to each key** grouped by tier.
- **Customizable audit warnings**.
- **Bulk actions**: add items to groups (projects), tag, revoke API keys, delete.
- **Custom properties** per credential: owner, contact, deployment...

And anything else the ArcGIS REST APIs let you do.

</details>

Find the [source code on GitHub](https://github.com/hhkaos/arcgis-credential-console).

[Embedded page](https://www.rauljimenez.info/arcgis-credential-console/?mock)

## The MVP

In this demo we will build a **minimal**, **barebones UI** using ArcGIS REST JS to:

- Add OAuth sign-in
- Search groups and credentials
- Display and manage groups
- Display credentials
- Manage API keys
- Add items (credentials) to groups

Everything it touches is either a group (A collection of items (and users) shared together. Here, one per customer project.) or an item (Any piece of content in ArcGIS: a map, a layer, a file… and **also a developer credential**.). 

> An API key is just an item with privileges and two keys.

At the top, you can see the steps ahead (You can open the index anytime. Use the icon at the bottom of this sidebar.). The "Output" panel runs the finished MVP.

## Load ArcGIS REST JS

[ArcGIS REST JS](https://developers.arcgis.com/arcgis-rest-js/) is a lightweight, modular JavaScript library for using the ArcGIS REST APIs in your browser and Node applications.

This MVP is a plain HTML page: no bundler and no build step, so the code on screen is all there is.

A CDN is great for a demo. In production you will likely install the packages from npm and use a bundler (Vite, webpack…): the code in the next steps doesn't change. See [other ways to install ArcGIS REST JS](https://developers.arcgis.com/arcgis-rest-js/install/#bundlers).

ArcGIS REST JS is **split into small packages**, so you only load what you use. This app needs:
* `arcgis-rest-request`: for sign-in and plain requests.
* `arcgis-rest-portal`: to manage items, groups and users.
* `arcgis-rest-developer-credentials`: to create, update and rotate API keys.

The import map lets the code use their npm names, loaded from a CDN.

The "Output" panel runs the finished MVP: sign in and try it with your account. Each of the next steps explains the ArcGIS REST JS code behind one part.

```html title="code/index.html" region="libs"
<!-- ArcGIS REST JS: only the packages this app uses -->
<script type="importmap">
  {
    "imports": {
      "@esri/arcgis-rest-request": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-request@4.11.0/+esm",
      "@esri/arcgis-rest-portal": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-portal@4.11.0/+esm",
      "@esri/arcgis-rest-developer-credentials": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-developer-credentials@4.11.0/+esm"
    }
  }
</script>
```

## Import what you use

`main.js` imports by npm name; the import map resolves each name to its CDN URL. With a bundler, the same lines work after `npm install`.

The functions are grouped by what they manage: sign-in, the user, projects (**groups**), credentials (**items**) and the **API keys** inside them.

<details>
<summary>What does REST JS do for you?</summary>

Each function wraps the REST API so you don't write `fetch` by hand:

- Adds the token and `f=json` to every request, and encodes the parameters.
- Throws an error you can `catch`. The REST API often answers HTTP 200 with the error inside the JSON. See [Error handling](https://developers.arcgis.com/arcgis-rest-js/error-handling/).
- Some functions make more than one request: `ArcGISIdentityManager` runs the whole OAuth flow and refreshes the token; `shareItemWithGroup` checks your role in the group before sharing.
- `SearchQueryBuilder` sends nothing: it only builds the query text.

To see it in action, open your browser's developer tools, go to the **Network** tab, filter by `www` and check the REST API requests that ArcGIS REST JS sends.

</details>

<details>
<summary>How much does it weigh?</summary>

Named imports pay off with a bundler: **tree shaking** drops every function you don't import.

- `request` alone: ~10 KB (min + gzip).
- The 16 imports this app uses: ~15.5 KB.
- The three packages in full: ~21.6 KB.

Measured with esbuild, REST JS 4.11.0. The CDN in this demo serves whole packages, so the savings only show up once you bundle.

</details>

```javascript title="code/main.js" region="imports"
// Sign-in: returns the session used by every call
// ErrorTypes: names of the errors REST JS throws
import { ArcGISIdentityManager, ErrorTypes } from "@esri/arcgis-rest-request";
import {
  getSelf,
  // Projects are groups
  searchGroups,
  createGroup,
  updateGroup,
  removeGroup,
  // Credentials are items
  searchItems,
  getGroupContent,
  updateItem,
  removeItem,
  shareItemWithGroup,
  SearchQueryBuilder,
} from "@esri/arcgis-rest-portal";
// API keys: the item plus its privileges, referrers and two key slots
import {
  createApiKey,
  getApiKey,
  updateApiKey, 
  invalidateApiKey,
} from "@esri/arcgis-rest-developer-credentials";
import { oauthOptions } from "./config.js";
```

## Start sign-in

When the user clicks the sign-in button, the app opens a popup where they sign in to the portal (The ArcGIS authentication server that signs users in and issues tokens. Here it is an ArcGIS Location Platform account. The same flow works with ArcGIS Online and ArcGIS Enterprise: set the `portal` option to point REST JS at it.) that holds their account. With a valid access token, the app can manage *their* groups and API keys.

[`ArcGISIdentityManager.beginOAuth2()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/ArcGISIdentityManager/) opens the ArcGIS sign-in page in a popup and returns a session (Holds the user's access token (30 minutes) and refresh token (2 weeks by default), and refreshes the access token for you.) once the popup finishes signing in. Its options, `oauthOptions`, live in `config.js`.

- OAuth 2.0 with PKCE (Proof Key for Code Exchange: a one-time secret created in the browser replaces the client secret.) needs no backend and no client secret.
- The session is what every REST JS call receives as `authentication`.
- `serialize()` saves the session to sessionStorage (It holds the token and the refresh token. Any script on the page can read browser storage, so one XSS steals the session. `sessionStorage` at least clears it when the tab closes; avoid `localStorage`.), so a reload keeps you signed in.

Try it in the Preview: press **Sign in with ArcGIS**, then **Cancel**. REST JS throws an `ArcGISAccessDeniedError`, and the app checks `error.name` against [`ErrorTypes`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/ErrorTypes/).

<details>
<summary>Which errors can REST JS throw?</summary>

- `ArcGISRequestError`: the base error. It carries the REST API `code`, the `url` and the raw `response`.
- `ArcGISAuthError`: invalid or expired token (codes 498/499). `retry()` sends the request again with a new session.
- `ArcGISTokenRequestError`: getting or refreshing a token failed.
- `ArcGISAccessDeniedError`: the user cancelled sign-in.

Compare `error.name` with `ErrorTypes`, as in [Error handling](https://developers.arcgis.com/arcgis-rest-js/error-handling/).

> **Note**: never log the whole error. Its `options` can hold credentials, like the password of a username/password session. Log `error.message` instead.

</details>

```javascript title="code/main.js" region="sign-in"
let session;
// XSS can read it: keep tokens server-side in production
const SESSION_KEY = "credential-console-basics-session";
const $ = (selector) => document.querySelector(selector);

$("#sign-in").addEventListener("click", async () => {
  try {
    // Opens the ArcGIS sign-in page in a popup (OAuth 2.0 with PKCE, no backend needed)
    session = await ArcGISIdentityManager.beginOAuth2(oauthOptions);
    sessionStorage.setItem(SESSION_KEY, session.serialize());
    showSignedIn();
  } catch (error) {
    // The user clicked Cancel on the ArcGIS sign-in page
    if (error.name === ErrorTypes.ArcGISAccessDeniedError) {
      $("#status").textContent = "Sign-in cancelled.";
      return;
    }
    $("#status").textContent = `Sign-in failed: ${error.message}`;
  }
});
```

## Configure OAuth

The portal must also know your app: create a developer credential ([**OAuth 2.0 credentials > For user authentication**](https://www.rauljimenez.info/arcgis-tutorials/arcgis-js-sdk-user-auth/#register-app)) with the right redirect URL and paste the **Client ID** here.

- **Client ID** (`clientId`)

- `portal`: where users sign in. The default works for ArcGIS Location Platform and ArcGIS Online; for ArcGIS Enterprise, use your portal's REST endpoint: `https://<host>/<webadaptor>/sharing/rest`.
- `redirectUri`: the page the portal sends the popup back to. Register this exact URL in the credential.
- `popup` (default true): sign in without leaving the app.

See all [OAuth 2.0 options](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/IOAuth2Options/#Properties).

`main.js` (`beginOAuth2`) and `callback.html` (`completeOAuth2`) import the same options, so both ends of the flow agree.

> When the popup opens, the portal reads the client ID and the redirect URL from the popup's address bar. If the redirect URL isn't registered in the developer credential of that client ID, the portal refuses to show the sign-in form.

```javascript title="code/config.js" region="config"
// callback.html, next to this page. Register this exact URL in your OAuth credentials.
const clientId = "YOUR_CLIENT_ID";
const redirectUri = new URL("callback.html", location.href).href;
console.log("redirectUri", redirectUri);

// OAuth options, shared by main.js (beginOAuth2) and callback.html (completeOAuth2)
export const oauthOptions = {
  // Client ID of your OAuth credentials
  clientId,
  redirectUri,
  
  // Set if you need to authenticate against ArcGIS Enterprise
  // portal: "https://<host>/<webadaptor>/sharing/rest", // Defaults to: https://www.arcgis.com/sharing/rest
  
  // Sign in in a popup , so the app stays on screen
  // popup: true
};
```

## Finish sign-in

After sign-in, the portal sends the short-lived authorization code to your **redirect URI**: `callback.html`.

[`ArcGISIdentityManager.completeOAuth2()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/ArcGISIdentityManager/) reads that authorization code from the URL, swaps it for a token, hands the session to the window that opened the popup and closes the popup.

> **Note**: It takes the same options as `beginOAuth2()`: both import them from `config.js`.

```html title="code/callback.html" region="callback"
import { ArcGISIdentityManager } from "@esri/arcgis-rest-request";
import { oauthOptions } from "./config.js";

// Same options as beginOAuth2. Hands the result back to the window
// that opened this popup and closes the popup.
ArcGISIdentityManager.completeOAuth2(oauthOptions);
```

## Get user info

[`getSelf()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/getSelf/) is the first authenticated request: it returns the signed-in user and their organization in one call. 

The app swaps **Sign in** for the user's full name and username.

Most REST JS functions return the plain JSON of the REST API. The `console.log` shows it once: explore it in the **Console** tab.

Try it in the Preview: press **Sign in with ArcGIS**.

<details>
<summary>Why "most"?</summary>

Some functions add to the REST API response:

- `searchGroups()` and `searchItems()` add `nextPage()` to fetch the next page of results.
- `getApiKey()` and `createApiKey()` merge the item and the credential into one object.

</details>

```javascript title="code/main.js" region="get-self"
async function showSignedIn() {
  // The signed-in user and the organization, in one request
  const self = await getSelf({ authentication: session });
  console.log("getSelf()", self);
  // The organization's own URL, e.g. https://<urlKey>.maps.arcgis.com
  portalHome = `https://${self.urlKey}.${self.customBaseUrl}`;
  $("#sign-in").hidden = true;
  $("#sign-out").hidden = false;
  const { username, fullName } = self.user;
  Object.assign($("#user"), { hidden: false, fullName, username });
  $("#new-project").disabled = false;
  loadProjects();
}
```

## Search groups

In the app, a **project** is a group tagged `project`. [`SearchQueryBuilder`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/SearchQueryBuilder/) builds the query from code: `tags:project AND owner:<you>`.

[`searchGroups()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/searchGroups/) returns the matches, and the Projects column lists them.

<details>
<summary>Why not write the query string by hand?</summary>

For a fixed query like this one, a string works. The builder pays off when:

- **Values have spaces**: `match("my project")` becomes `tags:"my project"`. By hand, `tags:my project` only matches `my`.
- **Filters are optional**: add each one inside an `if` instead of joining strings.
- **Dates**: `.from(date).to(date)` turns `Date` objects into a `[start TO end]` range.

```js
const q = new SearchQueryBuilder().match(session.username).in("owner");
if (tag) q.and().match(tag).in("tags");
if (since) q.and().from(since).to(new Date()).in("modified");
// owner:<you> AND tags:"my project" AND modified:[1767222000000 TO 1780264800000]
```

- **Groups and operators**: `startGroup()`/`endGroup()` add parentheses, and `or()` and `not()` work like `and()`. `not()` replaces `and()`: `.and().not()` logs a warning and drops the `NOT`.

```js
new SearchQueryBuilder()
  .match(session.username).in("owner")
  .and().startGroup()
    .match("project").in("tags").or().match("demo").in("tags")
  .endGroup()
  .not().match("archived").in("tags");
// owner:<you> AND (tags:project OR tags:demo) NOT tags:archived
```

- **Reuse**: `clone()` copies a base query, so you can add filters to the copy without changing the original.

</details>

```javascript title="code/main.js" region="search-groups"
// Groups with this tag are projects, as in Credential Console
const projectTag = "project";
// Not a group: a first entry in the Projects column that lists every item you own
const ALL = { id: "all", title: "All API keys" };
let projects = [];

async function loadProjects() {
  // Build the query from code: tags:project AND owner:<you>
  const q = new SearchQueryBuilder()
    .match(projectTag).in("tags")
    .and().match(session.username).in("owner");
  console.log("query", q.toParam());
  const response = await searchGroups({
    q, // Required
    num: 100,
    authentication: session,
  });
  console.log("searchGroups()", response);
  projects = response.results;
  selectProject(ALL.id);
  renderProjects();
}
```

## Create a group

[`createGroup()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/createGroup/) takes the group's title, tags and access, and returns the new group.

The search index takes a few seconds to see new groups, so the app adds it to the list itself instead of searching again.

```javascript title="code/main.js" region="create-group"
$("#new-project").addEventListener("click", async () => {
  const title = prompt("Project name");
  if (!title) return;
  const { group } = await createGroup({
    group: {
      title, // Required
      access: "private", // Required
      tags: [projectTag],
    },
    authentication: session,
  });
  // Search takes a few seconds to see new groups: add it to the list ourselves
  projects.push(group);
  selectProject(group.id);
  renderProjects();
});
```

## Update a group

[`updateGroup()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/updateGroup/) only needs the group's `id` and the fields that change. Rename a project in the Preview, then check **Groups** in your portal.

```javascript title="code/main.js" region="update-group"
async function renameProject(project) {
  const title = prompt("New project name", project.title);
  if (!title) return;
  await updateGroup({
    group: {
      id: project.id, // Required
      title,
    },
    authentication: session,
  });
  project.title = title;
  renderProjects();
}
```

## Halfway there

Sign-in and projects are done: the same few functions search, create and update any **group**.

Next, the credentials.

## Search credentials

Credentials are items, so they are found like any other item: [`searchItems()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/searchItems/) with a [`SearchQueryBuilder`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/SearchQueryBuilder/) query, here filtered to the credential type.

- Every developer credential is an item of type `Application`.
- API keys also carry the `APIToken` [type keyword (Type keywords describe the type and should logically apply to all items of that type.)](https://developers.arcgis.com/rest/users-groups-and-items/common-parameters/). like the one you sign in with, don't.

> **Note**: `searchItems()` also finds any content you own: maps, layers, documents, etc.

<details>
<summary>What if an option is missing?</summary>

The REST API sometimes supports a parameter that the function doesn't declare. Pass it in `params`: every REST JS function sends it as is.

```js
const response = await searchItems({
  q,
  authentication: session,
  params: { bbox: "-10,35,5,44" }, // supported by the REST API, not declared by searchItems()
});
```

Don't pass it at the top level: `searchItems({ q, bbox: "..." })` drops `bbox` without an error.

If REST JS has no function for an endpoint, call [`request()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/request/) directly. It still adds the token and `f=json`, and throws on errors.

</details>

<details>
<summary>More than 100 API keys?</summary>

`num` returns 100 results at most. When there are more, the response includes `nextPage()`: it repeats the search from where the last page ended.

```js
let response = await searchItems({ q, num: 100, authentication: session });
const results = [...response.results];
while (response.nextPage) {
  response = await response.nextPage();
  results.push(...response.results);
}
```

`nextPage()` reuses the same options (`q`, `num`, `authentication`), so every page sees the same items. `searchGroups()` works the same way.

</details>

```javascript title="code/main.js" region="search-credentials"
async function searchMyApiKeys() {
  // Search takes a few seconds to see changes
  const q = new SearchQueryBuilder()
    .match(session.username).in("owner")
    .and().match("Application").in("type") // every developer credential
    .and().match("APIToken").in("typekeywords"); // only API keys, not OAuth credentials
  const response = await searchItems({
    q, // Required
    num: 100,
    sortField: "modified",
    sortOrder: "desc",
    authentication: session,
  });
  console.log("searchItems()", response);
  return response.results;
}
```

## Read an API key

The item says what a credential is; the credential itself (privileges, referrers, which key slots are active) lives in the **registered app**. [`getApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/getApiKey/) reads both and merges them into one object.

Sometimes REST JS returns more than the REST API reference documents. `isPersonalAPIToken` is in the response, but not in the [Registered App](https://developers.arcgis.com/rest/users-groups-and-items/registered-app/) reference. Log the response and explore it.

The app also shows when each active key expires. The dates come from the item in the response, read directly rather than from the search index, so they are up to date.

Try it in the Preview: press the **Info** icon of an API key and open the **Console** tab.

<details>
<summary>No function for what you want? Use `request()`</summary>

Some data of special items lives in a REST endpoint that no REST JS function wraps. The expiration date of each API key is one: the item's `apiToken1ExpirationDate` and `apiToken2ExpirationDate` fields can be `-1` or out of date in search results.

[`request()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-request/request/), from `arcgis-rest-request`, calls any endpoint with the same session: it adds the token and `f=json`, encodes the parameters (dates included) and throws on errors.

```js
import { request } from "@esri/arcgis-rest-request";

const DAY = 24 * 60 * 60 * 1000;
// Every API key of the organization expiring in this window, both slots, in one request
const { items = [] } = await request(`${session.portal}/portals/self/apiTokens`, {
  authentication: session,
  params: {
    num: 100,
    startExpirationDate: new Date(Date.now() - 365 * DAY),
    endExpirationDate: new Date(Date.now() + 400 * DAY),
  },
});
// [{ itemId, apiToken: 1 | 2, expirationDate, title, owner, ... }]
```

</details>

```javascript title="code/main.js" region="get-api-key"
async function showApiKeyInfo(item) {
  // Credential + item in one call. Never includes the keys: safe to log
  const apiKey = await getApiKey({
    itemId: item.id, // Required
    authentication: session,
  });
  console.log(`getApiKey()`, apiKey);
  // Expiration dates are item fields (milliseconds). Only active slots hold a key that expires.
  item.expires = [1, 2]
    .filter((slot) => apiKey[`apiToken${slot}Active`])
    .map((slot) => `Key ${slot} expires ${new Date(apiKey.item[`apiToken${slot}ExpirationDate`]).toLocaleDateString()}`)
    .join(" · ") || "No active keys";
  renderItems();
}
```

## Create an API key

[`createApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/createApiKey/), from `arcgis-rest-developer-credentials`, creates the credential item with its privileges (What the key can do: use services such as basemaps or geocoding, and access specific items.), optional referrers (The websites allowed to use the key, e.g. `https://*.customer.com`. Avoid paths: browsers may strip them.) and expiration, and can generate its first API key.

The response is the only time the key can be read: the app shows it once so you can copy it, and keeps only the item. Never log it or store it in the browser.

Every key expires: here, in 30 days (one year at most).

```javascript title="code/main.js" region="create-api-key"
// What the keys of this demo can do: show basemaps
const privileges = ["premium:user:basemaps"];
// Keys always expire (one year at most). Here: in 30 days.
const in30Days = () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

$("#new-item").addEventListener("click", async () => {
  const title = prompt("API key title");
  if (!title) return;
  // Creates the item, registers it as a credential and generates the key in slot 1
  const apiKey = await createApiKey({
    title, // Required
    privileges, // Required
    tags: ["credential-console-basics"],
    generateToken1: true,
    apiToken1ExpirationDate: in30Days(),
    authentication: session,
  });
  // The only time the key can be read: the app doesn't keep it
  prompt("Copy the API key now. It won't be shown again.", apiKey.accessToken1);
  if (selectedProject !== ALL) {
    // Share it with the selected project: that's how keys are organized by customer
    await shareItemWithGroup({
      id: apiKey.itemId, // Required
      groupId: selectedProject.id, // Required
      authentication: session,
    });
  }
  items.push(apiKey.item);
  renderItems();
});
```

## Update the item

An API key is an item, so its title, tags and summary change with the generic [`updateItem()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/updateItem/). Only send the fields that change.

These fields are safe to edit: they don't affect the API keys.

```javascript title="code/main.js" region="update-item"
async function renameItem(item) {
  const title = prompt("New API key title", item.title);
  if (!title) return;
  // Item fields: don't touch the keys
  await updateItem({
    item: {
      id: item.id, // Required
      title,
    },
    authentication: session,
  });
  item.title = title;
  renderItems();
}
```

## Update privileges and referrers

What a key can do (**privileges**) and where it can be used from (**referrers**) are not item fields: they change with [`updateApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/updateApiKey/). Each list replaces the previous one, so send it whole.

Careful: changing privileges or referrers invalidates the existing keys. Customers need new ones.

```javascript title="code/main.js" region="update-api-key"
async function updatePrivilegesAndReferrers(item) {
  const referrers = prompt(
    "Websites allowed to use the key, comma separated (empty: any)",
    "https://*.example.com,https://yourdomain.com",
  );
  if (referrers === null) return;
  // Credential fields, not item fields. Lists replace: send them whole
  await updateApiKey({
    itemId: item.id, // Required
    privileges,
    httpReferrers: referrers.split(",").map((r) => r.trim()).filter(Boolean),
    authentication: session,
  });
  // Both keys stop working: the customer needs a new one (next step)
  $("#status").textContent = `"${item.title}" updated. Its keys no longer work: rotate it.`;
}
```

## Rotate an API key

Each credential has two key slots, so keys rotate without downtime. [`getApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/getApiKey/) tells which slot is in use, then:

1. [`updateApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/updateApiKey/) generates a new key in the free slot.
2. The customer switches to the new key.
3. [`invalidateApiKey()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-developer-credentials/invalidateApiKey/) revokes the old one.

```javascript title="code/main.js" region="rotate-api-key"
async function rotateApiKey(item) {
  // Which slot holds the key in use? The new key goes in the other one.
  const { apiToken1Active, apiToken2Active } = await getApiKey({
    itemId: item.id, // Required
    authentication: session,
  });
  const [newSlot, oldSlot] = apiToken1Active ? [2, 1] : [1, 2];
  // 1. Generate the new key: the old one keeps working meanwhile
  const updated = await updateApiKey({
    itemId: item.id, // Required
    [`generateToken${newSlot}`]: true,
    [`apiToken${newSlot}ExpirationDate`]: in30Days(),
    authentication: session,
  });
  // 2. The customer switches to the new key
  prompt(`New key in slot ${newSlot}. Copy it now: it won't be shown again.`, updated[`accessToken${newSlot}`]);
  // 3. Revoke the old key. It stops working in about a second.
  const oldKeyActive = oldSlot === 1 ? apiToken1Active : apiToken2Active;
  if (oldKeyActive && confirm(`Revoke the old key in slot ${oldSlot}?`)) {
    await invalidateApiKey({
      itemId: item.id, // Required
      apiKey: oldSlot,
      authentication: session,
    });
  }
}
```

## Clean up

[`removeItem()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/removeItem/) deletes an item, and [`removeGroup()`](https://developers.arcgis.com/arcgis-rest-js/api-reference/arcgis-rest-portal/removeGroup/) deletes a group. Deleting a group keeps its items in your content, so remove items first if you want both gone.

```javascript title="code/main.js" region="clean-up"
async function deleteItem(item) {
  if (!confirm(`Delete API key "${item.title}"? Apps using it stop working.`)) return;
  await removeItem({
    id: item.id, // Required
    authentication: session,
  });
  items = items.filter((i) => i.id !== item.id);
  renderItems();
}

async function deleteProject(project) {
  if (!confirm(`Delete project "${project.title}"? Its API keys stay in your content.`)) return;
  await removeGroup({
    id: project.id, // Required
    authentication: session,
  });
  projects = projects.filter((p) => p.id !== project.id);
  selectProject(ALL.id);
  renderProjects();
}
```

## Congratulations, you are done!

With a handful of REST JS functions you have the skeleton of Credential Console: sign-in, groups as projects, and API keys as items you create, update, rotate and organize.

The full app adds audits, usage and more on top of the same calls.

[Source code of the full app](https://github.com/hhkaos/arcgis-credential-console)

Questions?

- About this demo/tutorial: use [the issues on this repo](https://github.com/hhkaos/arcgis-tutorials/issues).
- For general questions about ArcGIS REST JS: use [its forum at Esri Community](https://community.esri.com/en/categories/arcgis-rest-js).

Check the [source code of the full reference app on GitHub](https://github.com/hhkaos/arcgis-credential-console).

## Final code

### code/index.html

```html title="code/index.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Credential Console · basics</title>
    <!-- Calcite components for the UI -->
    <link rel="stylesheet" href="https://js.arcgis.com/calcite-components/5.1.2/main.css" />
    <script type="module" src="https://js.arcgis.com/calcite-components/5.1.2/index.js"></script>
    <!-- ArcGIS REST JS: only the packages this app uses -->
    <script type="importmap">
      {
        "imports": {
          "@esri/arcgis-rest-request": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-request@4.11.0/+esm",
          "@esri/arcgis-rest-portal": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-portal@4.11.0/+esm",
          "@esri/arcgis-rest-developer-credentials": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-developer-credentials@4.11.0/+esm"
        }
      }
    </script>
    <link rel="stylesheet" href="./style.css" />
    <script type="module" src="./main.js"></script>
  </head>
  <body class="calcite-mode-auto">
    <calcite-shell>
      <calcite-navigation slot="header">
        <calcite-navigation-logo slot="logo" icon="key" heading="Credential Console" description="ArcGIS REST JS basics"></calcite-navigation-logo>
        <calcite-button slot="content-end" id="sign-in" icon-start="sign-in">Sign in with ArcGIS</calcite-button>
        <calcite-button slot="content-end" id="sign-out" icon-start="sign-out" appearance="transparent" hidden>Sign out</calcite-button>
        <calcite-navigation-user slot="user" id="user" hidden></calcite-navigation-user>
      </calcite-navigation>

      <!-- Projects = ArcGIS groups -->
      <calcite-shell-panel slot="panel-start">
        <calcite-panel heading="Projects" description="Your ArcGIS groups">
          <calcite-list id="projects" label="Projects" selection-mode="single" selection-appearance="highlight"></calcite-list>
          <calcite-button slot="footer" id="new-project" icon-start="plus" appearance="outline" width="full" disabled>New project</calcite-button>
        </calcite-panel>
      </calcite-shell-panel>

      <!-- API keys (items) of the selected project -->
      <calcite-panel id="items-panel" heading="API keys" description="Shared with the project">
        <calcite-button slot="header-actions-end" id="new-item" icon-start="plus" disabled>New API key</calcite-button>
        <calcite-list id="items" label="API keys"></calcite-list>
        <p id="status" class="status">Sign in to see your projects and API keys.</p>
      </calcite-panel>
    </calcite-shell>
  </body>
</html>
```

### code/main.js

```javascript title="code/main.js"
// Sign-in: returns the session used by every call
// ErrorTypes: names of the errors REST JS throws
import { ArcGISIdentityManager, ErrorTypes } from "@esri/arcgis-rest-request";
import {
  getSelf,
  // Projects are groups
  searchGroups,
  createGroup,
  updateGroup,
  removeGroup,
  // Credentials are items
  searchItems,
  getGroupContent,
  updateItem,
  removeItem,
  shareItemWithGroup,
  SearchQueryBuilder,
} from "@esri/arcgis-rest-portal";
// API keys: the item plus its privileges, referrers and two key slots
import {
  createApiKey,
  getApiKey,
  updateApiKey, 
  invalidateApiKey,
} from "@esri/arcgis-rest-developer-credentials";
import { oauthOptions } from "./config.js";

let session;
// XSS can read it: keep tokens server-side in production
const SESSION_KEY = "credential-console-basics-session";
const $ = (selector) => document.querySelector(selector);

$("#sign-in").addEventListener("click", async () => {
  try {
    // Opens the ArcGIS sign-in page in a popup (OAuth 2.0 with PKCE, no backend needed)
    session = await ArcGISIdentityManager.beginOAuth2(oauthOptions);
    sessionStorage.setItem(SESSION_KEY, session.serialize());
    showSignedIn();
  } catch (error) {
    // The user clicked Cancel on the ArcGIS sign-in page
    if (error.name === ErrorTypes.ArcGISAccessDeniedError) {
      $("#status").textContent = "Sign-in cancelled.";
      return;
    }
    $("#status").textContent = `Sign-in failed: ${error.message}`;
  }
});

async function showSignedIn() {
  // The signed-in user and the organization, in one request
  const self = await getSelf({ authentication: session });
  console.log("getSelf()", self);
  // The organization's own URL, e.g. https://<urlKey>.maps.arcgis.com
  portalHome = `https://${self.urlKey}.${self.customBaseUrl}`;
  $("#sign-in").hidden = true;
  $("#sign-out").hidden = false;
  const { username, fullName } = self.user;
  Object.assign($("#user"), { hidden: false, fullName, username });
  $("#new-project").disabled = false;
  loadProjects();
}

// Groups with this tag are projects, as in Credential Console
const projectTag = "project";
// Not a group: a first entry in the Projects column that lists every item you own
const ALL = { id: "all", title: "All API keys" };
let projects = [];

async function loadProjects() {
  // Build the query from code: tags:project AND owner:<you>
  const q = new SearchQueryBuilder()
    .match(projectTag).in("tags")
    .and().match(session.username).in("owner");
  console.log("query", q.toParam());
  const response = await searchGroups({
    q, // Required
    num: 100,
    authentication: session,
  });
  console.log("searchGroups()", response);
  projects = response.results;
  selectProject(ALL.id);
  renderProjects();
}

// Fills the Projects column: one entry per group, with Rename and Delete actions
function renderProjects() {
  render($("#projects"), projects, (p) => p.snippet ?? "", [
    ["launch", "Open in ArcGIS", openPortalPage("group")],
    ["pencil", "Rename", renameProject],
    ["trash", "Delete", deleteProject],
  ]);
  $("#projects").prepend(listItem(ALL, "Every API key you own", []));
}

$("#new-project").addEventListener("click", async () => {
  const title = prompt("Project name");
  if (!title) return;
  const { group } = await createGroup({
    group: {
      title, // Required
      access: "private", // Required
      tags: [projectTag],
    },
    authentication: session,
  });
  // Search takes a few seconds to see new groups: add it to the list ourselves
  projects.push(group);
  selectProject(group.id);
  renderProjects();
});

async function renameProject(project) {
  const title = prompt("New project name", project.title);
  if (!title) return;
  await updateGroup({
    group: {
      id: project.id, // Required
      title,
    },
    authentication: session,
  });
  project.title = title;
  renderProjects();
}

// The items of the selected project
let items = [];

// Runs each time a project is selected in the list
async function loadItems(project) {
  items = project === ALL ? await searchMyApiKeys() : await loadGroupItems(project);
  renderItems();
}

async function searchMyApiKeys() {
  // Search takes a few seconds to see changes
  const q = new SearchQueryBuilder()
    .match(session.username).in("owner")
    .and().match("Application").in("type") // every developer credential
    .and().match("APIToken").in("typekeywords"); // only API keys, not OAuth credentials
  const response = await searchItems({
    q, // Required
    num: 100,
    sortField: "modified",
    sortOrder: "desc",
    authentication: session,
  });
  console.log("searchItems()", response);
  return response.results;
}

async function loadGroupItems(project) {
  const response = await getGroupContent(project.id, { authentication: session });
  return response.items;
}

// Fills the API keys column: one entry per item, with one action per next step
function renderItems() {
  // Shows the expiration dates once the Info action has read them, the item type until then
  render($("#items"), items, (i) => i.expires ?? i.type, [
    ["launch", "Open in ArcGIS", openPortalPage("item")],
    ["information", "Info", showApiKeyInfo],
    ["pencil", "Rename", renameItem],
    ["globe", "Referrers", updatePrivilegesAndReferrers],
    ["refresh", "Rotate", rotateApiKey],
    ["trash", "Delete", deleteItem],
  ]);
  $("#status").textContent = items.length ? "" : "No API keys yet. Create one.";
}

async function showApiKeyInfo(item) {
  // Credential + item in one call. Never includes the keys: safe to log
  const apiKey = await getApiKey({
    itemId: item.id, // Required
    authentication: session,
  });
  console.log(`getApiKey()`, apiKey);
  // Expiration dates are item fields (milliseconds). Only active slots hold a key that expires.
  item.expires = [1, 2]
    .filter((slot) => apiKey[`apiToken${slot}Active`])
    .map((slot) => `Key ${slot} expires ${new Date(apiKey.item[`apiToken${slot}ExpirationDate`]).toLocaleDateString()}`)
    .join(" · ") || "No active keys";
  renderItems();
}

// What the keys of this demo can do: show basemaps
const privileges = ["premium:user:basemaps"];
// Keys always expire (one year at most). Here: in 30 days.
const in30Days = () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

$("#new-item").addEventListener("click", async () => {
  const title = prompt("API key title");
  if (!title) return;
  // Creates the item, registers it as a credential and generates the key in slot 1
  const apiKey = await createApiKey({
    title, // Required
    privileges, // Required
    tags: ["credential-console-basics"],
    generateToken1: true,
    apiToken1ExpirationDate: in30Days(),
    authentication: session,
  });
  // The only time the key can be read: the app doesn't keep it
  prompt("Copy the API key now. It won't be shown again.", apiKey.accessToken1);
  if (selectedProject !== ALL) {
    // Share it with the selected project: that's how keys are organized by customer
    await shareItemWithGroup({
      id: apiKey.itemId, // Required
      groupId: selectedProject.id, // Required
      authentication: session,
    });
  }
  items.push(apiKey.item);
  renderItems();
});

async function renameItem(item) {
  const title = prompt("New API key title", item.title);
  if (!title) return;
  // Item fields: don't touch the keys
  await updateItem({
    item: {
      id: item.id, // Required
      title,
    },
    authentication: session,
  });
  item.title = title;
  renderItems();
}

async function updatePrivilegesAndReferrers(item) {
  const referrers = prompt(
    "Websites allowed to use the key, comma separated (empty: any)",
    "https://*.example.com,https://yourdomain.com",
  );
  if (referrers === null) return;
  // Credential fields, not item fields. Lists replace: send them whole
  await updateApiKey({
    itemId: item.id, // Required
    privileges,
    httpReferrers: referrers.split(",").map((r) => r.trim()).filter(Boolean),
    authentication: session,
  });
  // Both keys stop working: the customer needs a new one (next step)
  $("#status").textContent = `"${item.title}" updated. Its keys no longer work: rotate it.`;
}

async function rotateApiKey(item) {
  // Which slot holds the key in use? The new key goes in the other one.
  const { apiToken1Active, apiToken2Active } = await getApiKey({
    itemId: item.id, // Required
    authentication: session,
  });
  const [newSlot, oldSlot] = apiToken1Active ? [2, 1] : [1, 2];
  // 1. Generate the new key: the old one keeps working meanwhile
  const updated = await updateApiKey({
    itemId: item.id, // Required
    [`generateToken${newSlot}`]: true,
    [`apiToken${newSlot}ExpirationDate`]: in30Days(),
    authentication: session,
  });
  // 2. The customer switches to the new key
  prompt(`New key in slot ${newSlot}. Copy it now: it won't be shown again.`, updated[`accessToken${newSlot}`]);
  // 3. Revoke the old key. It stops working in about a second.
  const oldKeyActive = oldSlot === 1 ? apiToken1Active : apiToken2Active;
  if (oldKeyActive && confirm(`Revoke the old key in slot ${oldSlot}?`)) {
    await invalidateApiKey({
      itemId: item.id, // Required
      apiKey: oldSlot,
      authentication: session,
    });
  }
}

async function deleteItem(item) {
  if (!confirm(`Delete API key "${item.title}"? Apps using it stop working.`)) return;
  await removeItem({
    id: item.id, // Required
    authentication: session,
  });
  items = items.filter((i) => i.id !== item.id);
  renderItems();
}

async function deleteProject(project) {
  if (!confirm(`Delete project "${project.title}"? Its API keys stay in your content.`)) return;
  await removeGroup({
    id: project.id, // Required
    authentication: session,
  });
  projects = projects.filter((p) => p.id !== project.id);
  selectProject(ALL.id);
  renderProjects();
}

// --- UI plumbing: not part of the tutorial steps ---

// The project selected in the Projects column
let selectedProject;

function selectProject(id) {
  selectedProject = id === ALL.id ? ALL : projects.find((p) => p.id === id);
  $("#new-item").disabled = !selectedProject;
  $("#items-panel").description = selectedProject ? selectedProject.title : "Select a project";
  items = [];
  renderItems();
  if (selectedProject) loadItems(selectedProject);
}

$("#projects").addEventListener("calciteListChange", (event) => {
  selectProject(event.target.selectedItems[0]?.value);
});

$("#sign-out").addEventListener("click", () => {
  sessionStorage.removeItem(SESSION_KEY);
  location.reload();
});

// A failed request shows its message (never log the whole error: it can hold credentials)
addEventListener("unhandledrejection", (event) => {
  $("#status").textContent = `Error: ${event.reason?.message ?? event.reason}`;
});

let portalHome;

// Opens the group or item page in the organization, to check the changes there
function openPortalPage(page) {
  return (record) => open(`${portalHome}/home/${page}.html?id=${record.id}`, "_blank");
}

// Generic list rendering, shared by projects and items
function render(list, records, describe, actions) {
  list.replaceChildren(...records.map((record) => listItem(record, describe(record), actions)));
}

function listItem(record, description, actions) {
  const element = document.createElement("calcite-list-item");
  Object.assign(element, { label: record.title, description, value: record.id, selected: record.id === selectedProject?.id });
  for (const [icon, text, onClick] of actions) {
    const action = Object.assign(document.createElement("calcite-action"), { icon, text, slot: "actions-end" });
    action.addEventListener("click", (event) => {
      event.stopPropagation();
      onClick(record);
    });
    element.append(action);
  }
  return element;
}

// Signed in before? Restore the session saved at sign-in (runs last: everything above is ready)
const saved = sessionStorage.getItem(SESSION_KEY);
if (saved) {
  session = ArcGISIdentityManager.deserialize(saved);
  showSignedIn();
}
```

### code/config.js

```javascript title="code/config.js"
// callback.html, next to this page. Register this exact URL in your OAuth credentials.
const clientId = "YOUR_CLIENT_ID";
const redirectUri = new URL("callback.html", location.href).href;
console.log("redirectUri", redirectUri);

// OAuth options, shared by main.js (beginOAuth2) and callback.html (completeOAuth2)
export const oauthOptions = {
  // Client ID of your OAuth credentials
  clientId,
  redirectUri,
  
  // Set if you need to authenticate against ArcGIS Enterprise
  // portal: "https://<host>/<webadaptor>/sharing/rest", // Defaults to: https://www.arcgis.com/sharing/rest
  
  // Sign in in a popup , so the app stays on screen
  // popup: true
};
```

### code/callback.html

```html title="code/callback.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Signing in…</title>
    <script type="importmap">
      { "imports": { "@esri/arcgis-rest-request": "https://cdn.jsdelivr.net/npm/@esri/arcgis-rest-request@4.11.0/+esm" } }
    </script>
  </head>
  <body>
    <p>Signing in…</p>
    <script type="module">
      import { ArcGISIdentityManager } from "@esri/arcgis-rest-request";
      import { oauthOptions } from "./config.js";

      // Same options as beginOAuth2. Hands the result back to the window
      // that opened this popup and closes the popup.
      ArcGISIdentityManager.completeOAuth2(oauthOptions);
    </script>
  </body>
</html>
```

### code/style.css

```css title="code/style.css"
html,
body {
  margin: 0;
  height: 100%;
}

body {
  background: var(--calcite-color-background);
  color: var(--calcite-color-text-1);
  font-family: var(--calcite-font-family);
}

.status {
  margin: 24px 16px;
  text-align: center;
  color: var(--calcite-color-text-3);
}

/* Calcite components set their own display, which overrides the hidden attribute */
[hidden] {
  display: none !important;
}
```
