メインコンテンツまでスキップ

Auth API reference

auth APIは、Momento auth tokens として知られる Momento サービスのauthトークンを作成し管理します。トークンは、1つ以上のキャッシュやトピックへのアクセスを許可するために、1つまたは複数の権限を持つように設定することができます。

GenerateApiKey API

権限と有効期限を指定することで新しい Momento authトークンを生成します。

名前説明
scopeTokenScope新しいトークンに付与する権限です。事前に組み立てられたTokenScopeオブジェクトがSDKによって提供されています。
expiresInNumber | ExpiresIn objectトークンが失効するまでの秒数、またはExpiresIn.never()、ExpiresIn.minutes()、ExpiresIn.hours()メソッドを呼び出すことで期間を表すExpiresInオブジェクトです。
Method response object
  • Success
    • authToken: string - 新しいauthトークン
    • refreshToken: string - 有効期限前にトークンを更新するために、RefreshApiKey APIと共に使用できるリフレッシュトークン
    • expiresAt: Timestamp - トークンが失効するタイムスタンプ
  • Error

具体的な情報についてはレスポンスオブジェクトをご覧ください。

注記

Momento のコントロールプレーン API にアクセスするためのトークンは、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

既存の有効な Momento authトークンを更新します。新しいauthトークンは、元のauthトークンと同じ権限と有効期間を持ちます。

名前説明
refreshTokenString現在のauthトークンのリフレッシュトークンで、これは GenerateApiKey の元の呼び出しから取得されます。
Method response object
  • Success
    • apiKey: string - 新しいauthトークン
    • refreshToken: string - 有効期限前にトークンを更新するために、RefreshApiKey API と共に使用できるリフレッシュトークン
    • expiresAt: Timestamp - トークンが失効するタイムスタンプ
  • Error

具体的な情報についてはレスポンスオブジェクトをご覧ください。

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

名前説明
permissionsList <Permission>新しいトークンに付与する権限です。

TokenScope は permission objectsのリストです。リストには、CachePermission型または TopicPermission型の権限が含まれ、最大で十のパーミッションオブジェクトを含むことができます。権限はMomento データプレーンAPI(例えば get、set など)へのアクセスのみを許可します。複数のパーミッションオブジェクトでauthトークンが作成されると、どの一致するパーミッションでもアクセスが許可されます。例えば、次の二つのパーミッションオブジェクトで単一のトークンが作成された場合:

  1. アカウントの全てのキャッシュに対して読み書きアクセスを許可するパーミッションオブジェクト
  2. キャッシュ foo への読み取り専用アクセスを許可するパーミッションオブジェクト

この場合、最初のパーミッションにより、キャッシュfooに対してデータ操作API(例えば setdeleteDictionarySetFieldsなど)の使用を許可するトークンになります。

Permission objects

これらのオブジェクトは、キャッシュまたはトピック情報に関する具体的なロールを定義し、その後 TokenScope に割り当てられます。

CachePermission

キャッシュに対する権限を定義する TokenScope オブジェクトの一部分。

名前説明
roleReadOnly | ReadWriteパーミッションにより付与されるアクセスの種類。
cacheAllCaches | CacheNameCacheName オブジェクトや AllCaches 組み込み値を使用して、パーミッションを選択したキャッシュ名に制限することができます。

ロールについては、CacheRole.ReadOnly を使用すると、CacheSelector で定義されたキャッシュのすべてのデータ読取りAPI(例:getDictionaryGetFieldなど)にアクセスできます。CacheRole.ReadWrite を使用すると、CacheSelector で定義されたキャッシュのすべての読み書きデータプレーンAPIへのアクセスが可能となります。カスタムロールはサポートされていません。

キャッシュについては、値は組み込みの AllCaches またはこのパーミッションが対象とするキャッシュの名前を含む文字列値にすることができます。

TopicPermission

トークンの権限を定義する TokenScope オブジェクトの一部分。

名前説明
roleSubscribeOnly | PublishSubscribeパーミッションにより付与されるアクセスの種類。
cacheAllCaches | CacheNameCacheName オブジェクトを使用してパーミッションを選択したキャッシュ名に制限したり、AllCaches 組み込み値を使用してアカウント内のすべてのキャッシュに制限することができます。
topicAllTopics | TopicNameTopicName オブジェクトを使用してパーミッションを選択したトピック名に制限したり、AllTopics 組み込み値を使用して上記キャッシュ内のすべてのトピックに制限することができます。

ロールについては、TopicRole.PublishSubscribeTopicRole.SubscribeOnly の2つの管理ロールを割り当てることができます。カスタムロールはサポートされていません。SubscribeOnly ロールを使用すると、トピックへのサブスクライブのみが許可されます。一方、PublishSubscribe ロールを使用すると、トピックへのパブリッシュとサブスクライブが許可されます。

キャッシュについては、そのキャッシュの名前空間内のトピックのみがパーミッションによって許可されます。これは組み込みの AllCaches 値に設定するか、特定のキャッシュの名前を指定する文字列に設定できます。

トピックについては、これは組み込みの AllTopics 値に設定でき、これはキャッシュで定義されたキャッシュ内のすべてのトピックへのアクセスを提供します。また、特定のトピック名を持つ文字列にすることもできます。

TopicScope examples

これは、CachePermissions のみで TokenScope を作成する例です。

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.
},
],
};

これは、TopicPermissions のみで TokenScope を作成する例です。

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, // Built-in 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).
},
],
};
ヒント

ここで答えられていない質問がある場合は、私たちのDiscordサーバーに参加し、サポートチャンネルで専門家に質問してください

FAQ

キャッシュまたはトピックのパーミッションに対してカスタムロールを作成することは可能ですか?

いいえ。各パーミッションについては、上記に列挙した管理されたロールのみをサポートしています。

これらのトークンは、Momento コントロールプレーン API へのアクセスを制御しますか?

GenerateApikey API で生成されたアクセストークンは、Momento のデータプレーンAPIへのアクセスだけを制御します。Momento のコントロールプレーンAPIへのアクセスのためのトークンは、Momento console を使用して生成する必要があります。

ヒント

ここで答えられない質問があれば、私たちのDiscordサーバーに飛び、サポートチャンネルで専門家に質問してください。