2
1

More than 1 year has passed since last update.

[Swift]AWSCognitoからログインユーザーの「idToken」「accessToken」「refreshToken」「deviceId」を取得する

Posted at

投稿の経緯

Amplify / Cognitoを利用してログイン機能を開発する機会があり、
公式ドキュメントを参考に

・idToken
・accessToken
・refreshToken
・deviceId

をCognitoから取得できたので記事にします。

前提

pod 'Amplify'
pod 'AmplifyPlugins/AWSCognitoAuthPlugin'

CocoapodsでもSPMでもなんでもいいですがSDKは導入している前提で記事を書いています。

実装

ライブラリをimportします

Hoge.swift
import AWSCore
import AWSCognitoIdentityProvider

amplifyconfiguration.jsonに記載されている値を参照してCognitoのPoolを設定します。
設定したPoolから現在ログインしているユーザー情報を取得することができます。

Hoge.swift
final class Hoge {

    private let clientId = "YOUR_CLIENT_ID"
    private let poolId = "YOUR_USER_POOL_ID"
    private let identityPoolId = "YOUR_IDENTITY_POOL_ID"
    private let clientSecret = "YOUR_CLIENT_SECRET"
    private let key = "UserPool"
    
    func hogehoge() {
        let configuration = AWSServiceConfiguration(region: .APNortheast1, credentialsProvider: nil)
        let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: clientId, clientSecret: "", poolId: poolId)
        AWSCognitoIdentityUserPool.register(with: configuration, userPoolConfiguration: userPoolConfiguration, forKey: key)
        let userPool = AWSCognitoIdentityUserPool(forKey: key)
        let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APNortheast1, identityPoolId: identityPoolId, identityProviderManager: userPool)
        guard let session = userPool?.currentUser()?.getSession() else {
            return
        }
        let task = session.continueWith { task in
            return task
        }
        
        if task.error != nil {
            print("Fail getCognitoUserData:", task.error as Any)
            return
        }
        
        guard let result = task.result as? AWSCognitoIdentityUserSession else {
            return
        }
    
        print("idToken", result.idToken?.tokenString as Any)
        print("accessToken", result.accessToken?.tokenString as Any)
        print("refreshToken", result.refreshToken?.tokenString as Any)
        print("deviceId", userPool?.currentUser()?.deviceIdentifier as Any)
    }
}

参考記事

おわりに

私はCognitoからユーザー情報を取得するドキュメントや記事を見つけるのに少し苦労しました。
最終的に公式ドキュメントに記載されていましたが、検索中は「なかなか記事がないな〜🤔」と感じていたのでこの記事が誰かの助けになれば幸いです。

最後までご覧いただきありがとうございました!

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1