Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ /

Create & Manage User API Keys - Web SDK

On this page

  • Overview
  • Create a User API Key
  • Look up a User API Key
  • Enable or Disable an API Key
  • Delete an API Key

You can use the Web SDK to create and manage user API keys that allow services to log in and interact with your app on behalf of an existing user without requiring the user to re-authenticate.

User API keys are managed as part of the API Key authentication provider but may only be created for users associated with a different, non-anonymous authentication provider.

User objects in the Web SDK include an ApiKeyAuth object that exposes methods to work with that user's API keys.

To create a new user API key, call ApiKeyAuth.create() with an identifying name for the key. The name must be a string that's unique among all of the user's API keys.

Warning

Store the API Key Value

The SDK only returns the value of the user API key when you create it. Make sure to store the key value securely so that you can use it to log in.

If you lose or do not store the key value there is no way to recover it. You will need to create a new user API key.

const user = app.currentUser;
const key = await user.apiKeys.create("myApiKey");

To get an array that lists all of a user's API keys, call ApiKeyAuth.fetchAll(). You can also find a specific API key by calling ApiKeyAuth.fetch() with the key's _id.

const user = app.currentUser;
// List all of a user's keys
const keys = await user.apiKeys.fetchAll();
// Get a specific key by its ID
const key = await user.apiKeys.fetch(API_KEY_ID);

You can enable or disable a user API key by calling ApiKeyAuth.enable() or ApiKeyAuth.disable() with the key's _id. When a key is disabled, it cannot be used to log in on behalf of the user.

// Get the ID of a User API Key
const user = app.currentUser;
const apiKeys = await user.apiKeys.fetchAll();
const keyId = apiKeys[0]["_id"];
// Enable the User API Key
await user.apiKeys.enable(keyId);
// Disable the User API Key
await user.apiKeys.disable(keyId);

You can permanently delete a user API key by calling ApiKeyAuth.delete() with the key's _id. Deleted keys can no longer be used to log in on behalf of the user.

// Get the ID of a User API Key
const user = app.currentUser;
const apiKeys = await user.apiKeys.fetchAll();
const keyId = apiKeys.find((key) => key.name === "apiKeyToDelete")._id;
// Delete the User API Key
await user.apiKeys.delete(keyId);

Back

Link User Identities

Next

Query MongoDB