Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.
Gen1 DocsLegacy

Page updated Mar 26, 2026

ユーザーセッションの管理

Amplify Authは、現在のユーザーセッションとトークンへのアクセスを提供し、ユーザー情報を取得して、有効なセッションでサインインしているかどうかを判断し、アプリケーションへのアクセスを制御するのに役立ちます。

Amplify Authの意図的な決定は、認証情報を公開したり操作したりするパブリックメソッドを避けることでした。

Authを使用すると、サインインするだけで、認証情報を最新の状態に保ち、他のカテゴリに提供するために必要なすべてが処理されます。

ただし、Amplify外のAPIを操作する場合や、AWS固有の識別情報 (例: IdentityId) にアクセスしたい場合は、以下のように fetchAuthSession の結果をキャストすることで、これらの実装詳細にアクセスできます。

import AWSPluginsCore
do {
let session = try await Amplify.Auth.fetchAuthSession()
// ユーザーのサブまたはアイデンティティIDを取得
if let identityProvider = session as? AuthCognitoIdentityProvider {
let usersub = try identityProvider.getUserSub().get()
let identityId = try identityProvider.getIdentityId().get()
print("User sub - \(usersub) and identity id \(identityId)")
}
// AWSの認証情報を取得
if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
let credentials = try awsCredentialsProvider.getAWSCredentials().get()
// 認証情報を使用して何かを行う
}
// Cognitoユーザープールトークンを取得
if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
let tokens = try cognitoTokenProvider.getCognitoTokens().get()
// JWTトークンを使用して何かを行う
}
} catch let error as AuthError {
print("Fetch auth session failed with error - \(error)")
} catch {
}

Cognito Identity Poolでゲストユーザーを有効にしていて、ユーザーがサインインしていない場合、identityIDとAWSの認証情報のみにアクセスできます。他のすべてのセッション詳細はエラーを返します。

import AWSPluginsCore
do {
let session = try await Amplify.Auth.fetchAuthSession()
// アイデンティティIDを取得
if let identityProvider = session as? AuthCognitoIdentityProvider {
let identityId = try identityProvider.getIdentityId().get()
print("Identity id \(identityId)")
}
// AWSの認証情報を取得
if let awsCredentialsProvider = session as? AuthAWSCredentialsProvider {
let credentials = try awsCredentialsProvider.getAWSCredentials().get()
// 認証情報を使用して何かを行う
}
} catch let error as AuthError {
print("Fetch auth session failed with error - \(error)")
} catch {
print("Unexpected error: \(error)")
}

セッションの強制更新

プラグインを通じて、fetchAuthSession APIを呼び出すときにAPIオプション forceRefresh を渡すことで、内部セッションを強制的に更新できます。

Amplify.Auth.fetchAuthSession(options: .forceRefresh())