ユーザーグループベースのデータアクセス
group 認可戦略を使用して、ユーザーグループに基づいてアクセスを制限できます。ユーザーグループ認可戦略により、特定のユーザーグループまたは各データレコードで動的に定義されたグループへのデータアクセスを制限できます。
特定のユーザーグループに対する認可ルールの追加
特定のユーザーグループセットへのアクセスを制限する場合、groups パラメータにグループ名を指定します。以下の例では、「Admin」ユーザーグループに属するユーザーのみが Salary モデルへのアクセスが許可されます。
// allow one specific groupconst schema = a.schema({ Salary: a .model({ wage: a.float(), currency: a.string(), }) .authorization(allow => [allow.group('Admin')]),});アプリケーションでは、client.models.<model-name> を使用して userPool 認証モードでモデルに対して CRUD 操作を実行できます。
import { generateClient } from 'aws-amplify/data';import type { Schema } from '../amplify/data/resource'; // Path to your backend resource definition
const client = generateClient<Schema>();
// As a signed-in user that belongs to the 'Admin' User Pool Groupconst { errors, data: newSalary } = await client.models.Salary.create( { wage: 50.25, currency: 'USD' }, { authMode: 'userPool', });この例では、複数の定義されたグループへのアクセスを許可するように更新できます。以下の例では「Leadership」へのアクセスを追加しました。
// allow multiple specific groupsconst schema = a.schema({ Salary: a .model({ wage: a.float(), currency: a.string(), }) .authorization(allow => [allow.groups(['Admin', 'Leadership'])]),});動的に設定されたユーザーグループに対する認可ルールの追加
動的グループ認可では、各レコードに、どの Cognito グループがそれにアクセスできるかを指定する属性が含まれます。最初の引数を使用して、基礎となるデータストアのどの属性がこのグループ情報を保持するかを指定します。単一のグループがアクセスできるように指定するには、a.string() 型のフィールドを使用します。複数のグループがアクセスできるように指定するには、a.string().array() 型のフィールドを使用します。
// Dynamic group authorization with multiple groupsconst schema = a.schema({ Post: a .model({ title: a.string(), groups: a.string().array(), }) .authorization(allow => [allow.groupsDefinedIn('groups')]),});// Dynamic group authorization with a single groupconst schema = a.schema({ Post: a .model({ title: a.string(), group: a.string(), }) .authorization(allow => [allow.groupDefinedIn('group')]),});デフォルトでは、group 認可は Amazon Cognito ユーザープールグループを使用しますが、group 認可で OpenID Connect を使用することもできます。認可プロバイダーとしての OpenID Connect を参照してください。
セッションからユーザーグループにアクセス
Auth カテゴリを使用してセッションからユーザーのグループにアクセスできます:
import { fetchAuthSession } from 'aws-amplify/auth';
const session = await fetchAuthSession();const groups = session.tokens.accessToken.payload['cognito:groups'] || [];
console.log('User groups:', groups);