Skip to main content

Auth API reference

The auth APIs create and manage API keys and tokens for Momento services. These auth mechanisms can be scoped to have one or more permissions to grant access to one or more caches or topics.

GenerateApiKey API

Generates a new Momento auth token with the specified permissions and expiry.

NameTypeDescription
scopeTokenScopeThe permissions to grant to the new token. Pre-built TokenScope objects are provided by the SDKs.
expiresInNumber  |  ExpiresIn objectThe number of seconds until the token expires or an ExpiresIn object representing a duration by calling the ExpiresIn.never(), ExpiresIn.minutes(), or ExpiresIn.hours() methods.
Method response object
  • Success
    • authToken: string - the new auth token
    • refreshToken: string - a refresh token that can be used with the RefreshApiKey API to refresh a token before it expires
    • endpoint: string - the HTTP endpoint the Momento client should use when making requests
    • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

See response objects for specific information.

note

Tokens to access the Momento control plane APIs can only be generated using the Momento console.

// Generate a token that allows all data plane APIs on all caches and topics.
const allDataRWTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));
if (allDataRWTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with AllDataReadWrite scope!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allDataRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${allDataRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${allDataRWTokenResponse.expiresAt.epoch()}`);
} else if (allDataRWTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with AllDataReadWrite scope: ${allDataRWTokenResponse.errorCode()}: ${allDataRWTokenResponse.toString()}`
);
}

// Generate a token that can only call read-only data plane APIs on a specific cache foo. No topic apis (publish/subscribe) are allowed.
const singleCacheROTokenResponse = await authClient.generateApiKey(
TokenScopes.cacheReadOnly('foo'),
ExpiresIn.minutes(30)
);
if (singleCacheROTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with read-only access to cache foo!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${singleCacheROTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${singleCacheROTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${singleCacheROTokenResponse.expiresAt.epoch()}`);
} else if (singleCacheROTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with single cache read-only scope: ${singleCacheROTokenResponse.errorCode()}: ${singleCacheROTokenResponse.toString()}`
);
}

// Generate a token that can call all data plane APIs on all caches. No topic apis (publish/subscribe) are allowed.
const allCachesRWTokenResponse = await authClient.generateApiKey(
TokenScopes.cacheReadWrite(AllCaches),
ExpiresIn.minutes(30)
);
if (allCachesRWTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with read-write access to all caches!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allCachesRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${allCachesRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${allCachesRWTokenResponse.expiresAt.epoch()}`);
} else if (allCachesRWTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with all caches read-write scope: ${allCachesRWTokenResponse.errorCode()}: ${allCachesRWTokenResponse.toString()}`
);
}

// Generate a token that can call publish and subscribe on all topics within cache bar
const singleCacheAllTopicsRWTokenResponse = await authClient.generateApiKey(
TokenScopes.topicPublishSubscribe({name: 'bar'}, AllTopics),
ExpiresIn.minutes(30)
);
if (singleCacheAllTopicsRWTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with publish-subscribe access to all topics within cache bar!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${singleCacheAllTopicsRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${singleCacheAllTopicsRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${singleCacheAllTopicsRWTokenResponse.expiresAt.epoch()}`);
} else if (singleCacheAllTopicsRWTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with read-write scope for all topics in a single cache: ${singleCacheAllTopicsRWTokenResponse.errorCode()}: ${singleCacheAllTopicsRWTokenResponse.toString()}`
);
}

// Generate a token that can only call subscribe on topic where_is_mo within cache mo_nuts
const oneCacheOneTopicRWTokenResponse = await authClient.generateApiKey(
TokenScopes.topicSubscribeOnly('mo_nuts', 'where_is_mo'),
ExpiresIn.minutes(30)
);
if (oneCacheOneTopicRWTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with subscribe-only access to topic where_is_mo within cache mo_nuts!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneCacheOneTopicRWTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${oneCacheOneTopicRWTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${oneCacheOneTopicRWTokenResponse.expiresAt.epoch()}`);
} else if (oneCacheOneTopicRWTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with read-write scope for single topic in a single cache: ${oneCacheOneTopicRWTokenResponse.errorCode()}: ${oneCacheOneTopicRWTokenResponse.toString()}`
);
}

// Generate a token with multiple permissions
const cachePermission1 = {
role: CacheRole.ReadWrite, // Managed role that grants access to read as well as write apis on caches
cache: 'acorns', // Scopes the access to a single cache named 'acorns'
};
const cachePermission2 = {
role: CacheRole.ReadOnly, // Managed role that grants access to only read data apis on caches
cache: AllCaches, // Built-in value for access to all caches in the account
};
const topicPermission1 = {
role: TopicRole.PublishSubscribe, // Managed role that grants access to subscribe as well as publish apis
cache: 'walnuts', // Scopes the access to a single cache named 'walnuts'
topic: 'mo_favorites', // Scopes the access to a single topic named 'mo_favorites' within cache 'walnuts'
};
const topicPermission2 = {
role: TopicRole.SubscribeOnly, // Managed role that grants access to only subscribe api
cache: AllCaches, // Built-in value for all cache(s) in the account.
topic: AllTopics, // Built-in value for access to all topics in the listed cache(s).
};

const permissions = {
permissions: [cachePermission1, cachePermission2, topicPermission1, topicPermission2],
};

const multiplePermsTokenResponse = await authClient.generateApiKey(permissions, ExpiresIn.minutes(30));
if (multiplePermsTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated an API key with multiple cache and topic permissions!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${multiplePermsTokenResponse.apiKey.substring(0, 10)}`);
console.log(`Refresh token starts with: ${multiplePermsTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Expires At: ${multiplePermsTokenResponse.expiresAt.epoch()}`);
} else if (multiplePermsTokenResponse instanceof GenerateApiKey.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with multiple permissions: ${multiplePermsTokenResponse.errorCode()}: ${multiplePermsTokenResponse.toString()}`
);
}

RefreshApiKey API

Refreshes an existing, unexpired Momento auth token. Produces a new auth token with the same permissions and expiry duration as the original auth token.

NameTypeDescription
refreshTokenStringThe refreshToken for the current auth token, acquired from the original call to GenerateAuthToken.
Method response object
  • Success
    • apiKey: string - the new auth token
    • refreshToken: string - a refresh token that can be used with the RefreshApiKey API to refresh the token before it expires
    • endpoint: string - the HTTP endpoint the Momento client should use when making requests
    • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

See response objects for specific information.

const generateTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));
if (generateTokenResponse instanceof GenerateApiKey.Success) {
console.log('Generated API key; refreshing!');
const refreshAuthClient = new AuthClient({
credentialProvider: CredentialProvider.fromString({apiKey: generateTokenResponse.apiKey}),
});
const refreshTokenResponse = await refreshAuthClient.refreshApiKey(generateTokenResponse.refreshToken);
if (refreshTokenResponse instanceof RefreshApiKey.Success) {
console.log('API key refreshed!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`Refreshed API key starts with: ${refreshTokenResponse.apiKey.substring(0, 10)}`);
console.log(`New refresh token starts with: ${refreshTokenResponse.refreshToken.substring(0, 10)}`);
console.log(`Refreshed API key expires At: ${refreshTokenResponse.expiresAt.epoch()}`);
}
}

TokenScope objects

NameTypeDescription
permissionsList <Permission>The permissions to grant to the new token.

A TokenScope is a list of permission objects. The list can have permissions that are of type CachePermission or TopicPermission, and can contain up to ten permission objects. A permission only grants access to the Momento data plane APIs (e.g. get, set, etc.). When an auth token is created with multiple permission objects, any matching permission will grant access. For example, if a single token is created with two permission objects:

  1. A permission object that allows ReadWrite access to all caches for the account
  2. A permission object that allows ReadOnly access to cache foo

In this case, the token will still allow use of data manipulation APIs (e.g. set, delete, DictionarySetFields, etc.) on cache foo because of the first permission.

Permission objects

These objects define the specific role with cache or topic information and are then assigned to a TokenScope.

CachePermission

A component of a TokenScope object that defines permissions for a cache.

NameTypeDescription
roleReadOnly  |  ReadWrite  |  WriteOnlyThe type of access granted by the permission.
cacheAllCaches  |  CacheNameA permission can be restricted to a select cache by name using a CacheName object or AllCaches built-in value.

For role, using CacheRole.ReadOnly allows access to all read data plane APIs on caches (e.g. get, DictionaryGetField, etc.) defined in the CacheSelector. Using CacheRole.ReadWrite allows access for all read and write data plane APIs on the caches defined in the CacheSelector. Using CacheRole.WriteOnly allows access for all write data plane APIs on the caches defined in the CacheSelector. CacheRole.WriteOnly cannot be used for APIs that imply conditional writes like SetIf* or return information about the updated state of a collection e.g. ListPushBack returns the new length. Custom roles are not supported.

For cache, the value can be the built-in AllCaches or a string value containing the name of the cache this permission is for.

TokenScope example for a CachePermission object

This is an example of creating a TokenScope with just CachePermissions.

const CachePermissions = {
permissions: [
{
role: CacheRole.ReadWrite, // Managed role
cache: "MyCache" // grants access to a specific cache
},
{
role: CacheRole.ReadOnly, // Managed role
cache: AllCaches // Built-in value for access to all caches in the account.
},
],
};

TopicPermission

A component of a TokenScope object that defines permissions for a token.

NameTypeDescription
roleSubscribeOnly | PublishSubscribe  |  PublishOnlyThe type of access granted by the permission.
cacheAllCaches  |  CacheNameA permission can be restricted to a select cache by name using a CacheName object or to all caches in the account by using the AllCaches built-in value.
topicAllTopics  |  TopicNameA permission can be restricted to a select topic by name using a TopicName object or to all topics in the above cache(s) by using the AllTopics built-in value.

For role, there are three managed roles to assign, TopicRole.PublishSubscribe, TopicRole.SubscribeOnly, and TopicRole.PublishOnly. Custom roles are not supported. Using the SubscribeOnly role allows only subscribing to topics, using the PublishSubscribe role allows publishing and subscribing to topics, and using the PublishOnly role allows only publishing to topics.

For cache, only topics within that cache's namespace are allowed by the permission. This can be set to the built-in AllCaches value or a string specifically naming a cache.

For topic, this can be set to the built-in AllTopics value, which gives access to all topics in the cache(s) defined in cache or it can be a string with a specific topic name.

TokenScope example for a TopicPermission object

This is an example of creating a TokenScope with just TopicPermissions.

const TopicsPermissions = {
permissions: [
{
role: TopicRole.PublishSubscribe, // Managed role
cache: 'the-great-wall', // grants access to a specific cache
topic: 'highlights', // grants access to a specific topic
},
{
role: TopicRole.SubscribeOnly, // Managed role
cache: AllCaches, // This is a built-in value for access to all caches in the account
topic: AllTopics, // This is a built-in value for access to all topic in the listed cache(s).
},
],
};

GenerateDisposableToken API

Generates a new disposable Momento auth token with the specified permissions and expiry.

Disposable tokens differ from the usual Momento auth token in several key ways:

  • They cannot be generated in the console, they can only be generated programatically. The token that's used for the generateDisposableToken API call must be a token with Super User scope generated via the Momento console.
  • They must expire within one hour.
  • They cannot be refreshed and thus do not come with a refresh token.
  • Permissions are specified using DisposableTokenScope object.
NameTypeDescription
scopeDisposableTokenScopeThe permissions to grant to the new disposable token. Pre-built DisposableTokenScope objects are provided by the SDKs.
expiresInNumber  |  ExpiresIn objectThe number of seconds until the token expires or an ExpiresIn object representing a duration by calling the ExpiresIn.minutes() or ExpiresIn.hours(1) methods. Disposable tokens must expire within 1 hour.
Method response object
  • Success
    • authToken: string - the new disposable auth token
    • endpoint: string - the HTTP endpoint the Momento client should use when making requests
    • expiresAt: Timestamp - the timestamp at which the token will expire
  • Error

See response objects for specific information.

// Generate a disposable token with read-write access to a specific key in one cache
const oneKeyOneCacheToken = await authClient.generateDisposableToken(
DisposableTokenScopes.cacheKeyReadWrite('squirrels', 'mo'),
ExpiresIn.minutes(30)
);
if (oneKeyOneCacheToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to the "mo" key in the "squirrels" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneKeyOneCacheToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${oneKeyOneCacheToken.expiresAt.epoch()}`);
} else if (oneKeyOneCacheToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${oneKeyOneCacheToken.errorCode()}: ${oneKeyOneCacheToken.toString()}`
);
}

// Generate a disposable token with read-write access to a specific key prefix in all caches
const keyPrefixAllCachesToken = await authClient.generateDisposableToken(
DisposableTokenScopes.cacheKeyPrefixReadWrite(AllCaches, 'squirrel'),
ExpiresIn.minutes(30)
);
if (keyPrefixAllCachesToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to keys prefixed with "squirrel" in all caches!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${keyPrefixAllCachesToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${keyPrefixAllCachesToken.expiresAt.epoch()}`);
} else if (keyPrefixAllCachesToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${keyPrefixAllCachesToken.errorCode()}: ${keyPrefixAllCachesToken.toString()}`
);
}

// Generate a disposable token with read-only access to all topics in one cache
const allTopicsOneCacheToken = await authClient.generateDisposableToken(
TokenScopes.topicSubscribeOnly('squirrel', AllTopics),
ExpiresIn.minutes(30)
);
if (allTopicsOneCacheToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to all topics in the "squirrel" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${allTopicsOneCacheToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${allTopicsOneCacheToken.expiresAt.epoch()}`);
} else if (allTopicsOneCacheToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${allTopicsOneCacheToken.errorCode()}: ${allTopicsOneCacheToken.toString()}`
);
}

// Generate a disposable token with write-only access to a single topic in all caches
const oneTopicAllCachesToken = await authClient.generateDisposableToken(
TokenScopes.topicPublishOnly(AllCaches, 'acorn'),
ExpiresIn.minutes(30)
);
if (oneTopicAllCachesToken instanceof GenerateDisposableToken.Success) {
console.log('Generated a disposable API key with access to all topics in the "squirrel" cache!');
// logging only a substring of the tokens, because logging security credentials is not advisable :)
console.log(`API key starts with: ${oneTopicAllCachesToken.authToken.substring(0, 10)}`);
console.log(`Expires At: ${oneTopicAllCachesToken.expiresAt.epoch()}`);
} else if (oneTopicAllCachesToken instanceof GenerateDisposableToken.Error) {
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${oneTopicAllCachesToken.errorCode()}: ${oneTopicAllCachesToken.toString()}`
);
}

DisposableTokenScope objects

NameTypeDescription
permissionsList <DisposableTokenCachePermission  |  Permission>The permissions to grant to the new token.

The DisposableTokenScope object will accept permissions objects of the type CachePermission, TopicPermission, or DisposableTokenCachePermission.

DisposableTokenCachePermissions

The DisposableTokenCachePermission is an extension of CachePermission, so it has the same fields as CachePermission but also has an additional item field so you can define permissions for a cache and the items within the cache.

For example, you can restrict access to only a specific key or a set of keys beginning with some prefix when you set item to a string that represents a key or key-prefix. Alternately, if you set item to AllCacheItems, you would produce the same set of permissions as a normal CachePermission.

NameTypeDescription
roleReadOnly  |  ReadWrite  |  WriteOnlyThe type of access granted by the permission.
cacheAllCaches  |  CacheNameA permission can be restricted to a select cache by name using a CacheName object or AllCaches built-in value.
itemAllCacheItems  |  Key  |  KeyPrefixA permission can be restricted to select cache items by name using a Key or KeyPrefix object or AllCachesItems built-in value.

For role, using CacheRole.ReadOnly allows access to all read data plane APIs on caches (e.g. get, DictionaryGetField, etc.) defined in the CacheSelector. Using CacheRole.ReadWrite allows access for all read and write data plane APIs on the caches defined in the CacheSelector. Using CacheRole.WriteOnly allows access for all write data plane APIs on the caches defined in the CacheSelector. CacheRole.WriteOnly cannot be used for APIs that imply conditional writes like SetIf* or return information about the updated state of a collection e.g. ListPushBack returns the new length. Custom roles are not supported.

For cache, the value can be the built-in AllCaches or a string value containing the name of the cache this permission is for.

For item, the value can be the built-in AllCacheItems or a string value containing the key or key prefix of the cache item(s) this permission is for.

Example DisposableTokenScope object

This is an example of creating a DisposableTokenScope with all three types of permission objects: CachePermission, TopicPermission, and DisposableTokenCachePermission.

const exampleDisposableTokenPermission: DisposableTokenCachePermission = {
role: CacheRole.WriteOnly,
cache: "WriteCache",
item: {
keyPrefix: "WriteKey"
}
};

const exampleCachePermission: CachePermission = {
role: CacheRole.ReadOnly,
cache: "ReadCache"
};

const exampleTopicPermission: TopicPermission = {
role: TopicRole.PublishSubscribe,
cache: "ReadWriteCache",
topic: "MyTopic"
}

const exampleScope: DisposableTokenScope = {
permissions: [
exampleDisposableTokenPermission,
exampleCachePermission,
exampleTopicPermission,
],
};

// Then pass in the entire DisposableTokenScope object when
// you call generateDisposableToken
const tokenResponse = await authClient.generateDisposableToken(
exampleScope,
ExpiresIn.minutes(30)
);

FAQ

Can I create a custom role for a cache or topic permission?

No. We only support the managed roles listed above for each permission.

Do these tokens control access to the Momento control plane APIs?

Access tokens generated with the GenerateApiKey API only control access to the Momento data plane APIs. A token for access to Momento's control plane APIs must be generated using the Momento console.

tip

If you have any questions not answered here, please jump on our Discord server and ask our experts in the support channel.