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.
AuthClient Methods
GenerateApiKey
Generates a new Momento auth token with the specified permissions and expiry.
Parameters
- scope - PermissionScope: The permissions to grant to the new token. Pre-built PermissionScope objects are provided by the SDKs.
- expiresIn - Number | ExpiresIn object: The number of seconds until the token expires or an ExpiresIn object representing a duration by calling the
ExpiresIn.never()
,ExpiresIn.minutes()
, orExpiresIn.hours()
methods.
Returns
One of the following:
-
Success:
authToken
: string - the new auth tokenrefreshToken
: string - a refresh token that can be used with the RefreshApiKey API to refresh a token before it expiresendpoint
: string - the HTTP endpoint the Momento client should use when making requestsexpiresAt
: Timestamp - the timestamp at which the token will expire
-
Error:
- See response objects for specific information.
- JavaScript
- Go
// Generate a token that allows all data plane APIs on all caches and topics.
const allDataRWTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));
switch (allDataRWTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.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)
);
switch (singleCacheROTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.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)
);
switch (allCachesRWTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.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)
);
switch (singleCacheAllTopicsRWTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.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)
);
switch (oneCacheOneTopicRWTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.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));
switch (multiplePermsTokenResponse.type) {
case GenerateApiKeyResponse.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()}`);
break;
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with multiple permissions: ${multiplePermsTokenResponse.errorCode()}: ${multiplePermsTokenResponse.toString()}`
);
}
// Generate a token that allows all data plane APIs on all caches and topics.
resp, err := authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.AllDataReadWrite,
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key with AllDataReadWrite scope!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
// Generate a token that can only call read-only data plane APIs on a specific cache foo. No topic apis (publish/subscribe) are allowed.
resp, err = authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.CacheReadOnly(momento.CacheName{Name: "foo"}),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key with read-only access to cache foo!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
// Generate a token that can call all data plane APIs on all caches. No topic apis (publish/subscribe) are allowed.
resp, err = authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.CacheReadWrite(momento.AllCaches{}),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key with read-write access to all caches!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
// Generate a token that can call publish and subscribe on all topics within cache bar
resp, err = authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.TopicPublishSubscribe(momento.CacheName{Name: "bar"}, momento.AllTopics{}),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key publish-subscribe access to all topics within cache bar!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
// Generate a token that can only call subscribe on topic where_is_mo within cache mo_nuts
resp, err = authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.TopicSubscribeOnly(momento.CacheName{Name: "mo_nuts"}, momento.TopicName{Name: "where_is_mo"}),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key with subscribe-only access to topic where_is_mo within cache mo_nuts!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
// Generate a token with multiple permissions
cachePermission1 := momento.CachePermission{
Cache: momento.CacheName{Name: "acorns"}, // Scopes the access to a single cache named 'acorns'
Role: momento.ReadWrite, // Managed role that grants access to read as well as write apis on caches
}
cachePermission2 := momento.CachePermission{
Cache: momento.AllCaches{}, // Built-in value for access to all caches in the account
Role: momento.ReadOnly, // Managed role that grants access to only read data apis on caches
}
topicPermission1 := momento.TopicPermission{
Cache: momento.CacheName{Name: "walnuts"}, // Scopes the access to a single cache named 'walnuts'
Topic: momento.TopicName{Name: "mo_favorites"}, // Scopes the access to a single topic named 'mo_favorites' within cache 'walnuts'
Role: momento.PublishSubscribe, // Managed role that grants access to subscribe as well as publish apis
}
topicPermission2 := momento.TopicPermission{
Cache: momento.AllCaches{}, // Built-in value for all cache(s) in the account.
Topic: momento.AllTopics{}, // Built-in value for access to all topics in the listed cache(s).
Role: momento.SubscribeOnly, // Managed role that grants access to only subscribe api
}
permissions := []momento.Permission{
cachePermission1, cachePermission2, topicPermission1, topicPermission2,
}
resp, err = authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.Permissions{
Permissions: permissions,
},
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateApiKeySuccess:
log.Printf("Successfully generated an API key with multiple cache and topic permissions!\n")
log.Printf("API key expires at: %d\n", r.ExpiresAt.Epoch())
}
RefreshApiKey
Refreshes an existing, unexpired Momento API key. Produces a new API key with the same permissions and expiry duration as the original API key.
Parameters
- refreshToken - string: The refresh token that was provided when the original API key was generated.
Returns
One of the following:
-
Success:
apiKey
: string - the new auth tokenrefreshToken
: string - a refresh token that can be used with the RefreshApiKey API to refresh a token before it expiresendpoint
: string - the HTTP endpoint the Momento client should use when making requestsexpiresAt
: Timestamp - the timestamp at which the token will expire
-
Error:
- See response objects for specific information.
- JavaScript
- Go
const generateTokenResponse = await authClient.generateApiKey(AllDataReadWrite, ExpiresIn.minutes(30));
let successResponse: GenerateApiKey.Success;
switch (generateTokenResponse.type) {
case GenerateApiKeyResponse.Success: {
successResponse = generateTokenResponse;
break;
}
case GenerateApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey: ${generateTokenResponse.errorCode()}: ${generateTokenResponse.toString()}`
);
}
console.log('Generated API key; refreshing!');
const refreshAuthClient = new AuthClient({
credentialProvider: CredentialProvider.fromString({apiKey: successResponse.apiKey}),
});
const refreshTokenResponse = await refreshAuthClient.refreshApiKey(successResponse.refreshToken);
switch (refreshTokenResponse.type) {
case RefreshApiKeyResponse.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()}`);
break;
case RefreshApiKeyResponse.Error:
throw new Error(
`An error occurred while attempting to call refreshApiKey: ${refreshTokenResponse.errorCode()}: ${refreshTokenResponse.toString()}`
);
}
resp, err := authClient.GenerateApiKey(ctx, &momento.GenerateApiKeyRequest{
ExpiresIn: utils.ExpiresInMinutes(30),
Scope: momento.AllDataReadWrite,
})
if err != nil {
panic(err)
}
generateApiKeySuccess := resp.(*auth_resp.GenerateApiKeySuccess)
newCredProvider, err := auth.FromString(generateApiKeySuccess.ApiKey)
if err != nil {
panic(err)
}
refreshAuthClient, err := momento.NewAuthClient(config.AuthDefault(), newCredProvider)
if err != nil {
panic(err)
}
refreshResp, err := refreshAuthClient.RefreshApiKey(ctx, &momento.RefreshApiKeyRequest{
RefreshToken: generateApiKeySuccess.RefreshToken,
})
if err != nil {
panic(err)
}
switch r := refreshResp.(type) {
case *auth_resp.RefreshApiKeySuccess:
log.Printf("Successfully refreshed API key!\n")
log.Printf("Refreshed API key expires at: %d\n", r.ExpiresAt.Epoch())
}
GenerateDisposableToken
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 programmatically. 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.
Parameters
- scope - DisposableTokenScope: The permissions to grant to the new disposable token. Pre-built DisposableTokenScope objects are provided by the SDKs.
- expiresIn - Number | ExpiresIn object: The 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.
Returns
One of the following:
-
Success:
authToken
: string - the new disposable auth tokenendpoint
: string - the HTTP endpoint the Momento client should use when making requestsexpiresAt
: Timestamp - the timestamp at which the token will expire
-
Error:
- See response objects for specific information.
- JavaScript
- Python
- Java
- Go
- C#
// 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)
);
switch (oneKeyOneCacheToken.type) {
case GenerateDisposableTokenResponse.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()}`);
break;
case GenerateDisposableTokenResponse.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)
);
switch (keyPrefixAllCachesToken.type) {
case GenerateDisposableTokenResponse.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()}`);
break;
case GenerateDisposableTokenResponse.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)
);
switch (allTopicsOneCacheToken.type) {
case GenerateDisposableTokenResponse.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()}`);
break;
case GenerateDisposableTokenResponse.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)
);
switch (oneTopicAllCachesToken.type) {
case GenerateDisposableTokenResponse.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()}`);
break;
case GenerateDisposableTokenResponse.Error:
throw new Error(
`An error occurred while attempting to call generateApiKey with disposable token scope: ${oneTopicAllCachesToken.errorCode()}: ${oneTopicAllCachesToken.toString()}`
);
}
response = await auth_client.generate_disposable_token(
DisposableTokenScopes.topic_publish_subscribe("a-cache", "a-topic"),
ExpiresIn.minutes(5),
DisposableTokenProps(token_id="a-token-id"),
)
match response:
case GenerateDisposableToken.Success():
print("Successfully generated a disposable token")
case GenerateDisposableToken.Error() as error:
print(f"Error generating a disposable token: {error.message}")
final GenerateDisposableTokenResponse response =
authClient
.generateDisposableTokenAsync(
DisposableTokenScopes.cacheKeyReadWrite("squirrel", "mo"), ExpiresIn.minutes(30))
.join();
if (response instanceof GenerateDisposableTokenResponse.Success success) {
System.out.println("Successfully generated the disposable token: " + success.authToken());
} else if (response instanceof GenerateDisposableTokenResponse.Error error) {
throw new RuntimeException(
"An error occurred while attempting to generate disposable token: "
+ error.getErrorCode(),
error);
}
tokenId := "a token id"
resp, err := authClient.GenerateDisposableToken(ctx, &momento.GenerateDisposableTokenRequest{
ExpiresIn: utils.ExpiresInSeconds(10),
Scope: momento.TopicSubscribeOnly(
momento.CacheName{Name: "a cache"},
momento.TopicName{Name: "a topic"},
),
Props: momento.DisposableTokenProps{
TokenId: &tokenId,
},
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *auth_resp.GenerateDisposableTokenSuccess:
log.Printf("Successfully generated a disposable token for endpoint=%s with tokenId=%s\n", r.Endpoint, tokenId)
}
// Generate a disposable token with read-write access to a specific key in one cache
var oneKeyOneCacheToken = await authClient.GenerateDisposableTokenAsync(
DisposableTokenScopes.CacheKeyReadWrite("squirrels", "mo"),
ExpiresIn.Minutes(30)
);
if (oneKeyOneCacheToken is GenerateDisposableTokenResponse.Success token1)
{
// logging only a substring of the tokens, because logging security credentials is not advisable :)
Console.WriteLine("The generated disposable token starts with: " + token1.AuthToken.Substring(0, 10));
Console.WriteLine("The token expires at (epoch timestamp): " + token1.ExpiresAt.Epoch());
}
else if (oneKeyOneCacheToken is GenerateDisposableTokenResponse.Error err)
{
Console.WriteLine("Error generating disposable token: " + err.Message);
}
// Generate a disposable token with read-write access to a specific key prefix in all caches
var keyPrefixAllCachesToken = await authClient.GenerateDisposableTokenAsync(
DisposableTokenScopes.CacheKeyPrefixReadWrite(CacheSelector.AllCaches, "squirrel"),
ExpiresIn.Minutes(30)
);
if (keyPrefixAllCachesToken is GenerateDisposableTokenResponse.Success token2)
{
// logging only a substring of the tokens, because logging security credentials is not advisable :)
Console.WriteLine("The generated disposable token starts with: " + token2.AuthToken.Substring(0, 10));
Console.WriteLine("The token expires at (epoch timestamp): " + token2.ExpiresAt.Epoch());
}
else if (keyPrefixAllCachesToken is GenerateDisposableTokenResponse.Error err)
{
Console.WriteLine("Error generating disposable token: " + err.Message);
}
// Generate a disposable token with read-only access to all topics in one cache
var allTopicsOneCacheToken = await authClient.GenerateDisposableTokenAsync(
DisposableTokenScopes.TopicSubscribeOnly("squirrel", TopicSelector.AllTopics),
ExpiresIn.Minutes(30)
);
if (allTopicsOneCacheToken is GenerateDisposableTokenResponse.Success token3)
{
// logging only a substring of the tokens, because logging security credentials is not advisable :)
Console.WriteLine("The generated disposable token starts with: " + token3.AuthToken.Substring(0, 10));
Console.WriteLine("The token expires at (epoch timestamp): " + token3.ExpiresAt.Epoch());
}
else if (allTopicsOneCacheToken is GenerateDisposableTokenResponse.Error err)
{
Console.WriteLine("Error generating disposable token: " + err.Message);
}
// Generate a disposable token with write-only access to a single topic in all caches
var oneTopicAllCachesToken = await authClient.GenerateDisposableTokenAsync(
DisposableTokenScopes.TopicPublishOnly(CacheSelector.AllCaches, "acorn"),
ExpiresIn.Minutes(30)
);
if (oneTopicAllCachesToken is GenerateDisposableTokenResponse.Success token4)
{
// logging only a substring of the tokens, because logging security credentials is not advisable :)
Console.WriteLine("The generated disposable token starts with: " + token4.AuthToken.Substring(0, 10));
Console.WriteLine("The token expires at (epoch timestamp): " + token4.ExpiresAt.Epoch());
}
else if (oneTopicAllCachesToken is GenerateDisposableTokenResponse.Error err)
{
Console.WriteLine("Error generating disposable token: " + err.Message);
}
PermissionScope objects
PermissionScope
Name | Type | Description |
---|---|---|
permissions | List <Permission> | The permissions to grant to the new token. |
A PermissionScope 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:
- A permission object that allows ReadWrite access to all caches for the account
- 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 PermissionScope.
CachePermission
A component of a PermissionScope object that defines permissions for a cache.
Name | Type | Description |
---|---|---|
role | ReadOnly | ReadWrite | WriteOnly | The type of access granted by the permission. |
cache | AllCaches | CacheName | A 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.
PermissionScope example for a CachePermission object
This is an example of creating a PermissionScope 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 PermissionScope object that defines permissions for a token.
Name | Type | Description |
---|---|---|
role | SubscribeOnly | PublishSubscribe | PublishOnly | The type of access granted by the permission. |
cache | AllCaches | CacheName | A 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. |
topic | AllTopics | TopicName | A 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.
PermissionScope example for a TopicPermission object
This is an example of creating a PermissionScope 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).
},
],
};
DisposableTokenScope objects
Name | Type | Description |
---|---|---|
permissions | List <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.
Name | Type | Description |
---|---|---|
role | ReadOnly | ReadWrite | WriteOnly | The type of access granted by the permission. |
cache | AllCaches | CacheName | A permission can be restricted to a select cache by name using a CacheName object or AllCaches built-in value. |
item | AllCacheItems | Key | KeyPrefix | A 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.
If you have any questions not answered here, please jump on our Discord server and ask our experts in the support channel.