ROADTO みちログ

ひとのみちのブログ。大阪でiOSアプリの道を歩くフリーランス。

CognitoIDを取得する方法

AWS Cognito の CognitoIDと呼ばれるモノを取得する方法を備忘録。
頑張ったけど使わなくなったのでここで供養。

CognitoのUserPoolのsubの値を取得する

    var pool: AWSCognitoIdentityUserPool?
    var credentialsProvider: AWSCognitoCredentialsProvider?

    func login() {

        let email = "メールアドレスの値"
        let password = "パスワードの値"

        // ユーザープールを取得する
        pool = AWSCognitoIdentityUserPool(forKey: "AWS USERPOOLのキー")
        // 認証する
        let user: AWSCognitoIdentityUser = pool!.getUser(email)
        user.getSession(email, password: password, validationData: nil).continueWith(block: {task in
            if task.error != nil {
                dLog("ログイン失敗:" + task.error.debugDescription)
            } else {
                dLog("ログイン成功")
                
                user.getDetails().continueWith(block: { (task: AWSTask) -> Any? in
                    if let response = task.result, let userAttributes = response.userAttributes {
                        
                        var cognitoId: String?
                        for userAttribute in userAttributes {
                            if userAttribute.name == "sub" {
                                cognitoId = userAttribute.value
                            }
                        }
                        
                        if let cognitoId = cognitoId {
                            
                            dLog("Cognito id: \(cognitoId)")
                            
                        } else {
                            dLog("ログイン失敗: Cognito id: nil")
                        }
                        
                    } else {
                        dLog("ログイン失敗: Cognito id: nil")
                    }
                    return nil
                })                
            }
            return nil
        })

Cognitoのフェデレーティッドアイデンティティアイデンティティ IDの値を取得する

    var pool: AWSCognitoIdentityUserPool?
    var credentialsProvider: AWSCognitoCredentialsProvider?

    func login() {

        let email = "メールアドレスの値"
        let password = "パスワードの値"

        // ユーザープールを取得する
        pool = AWSCognitoIdentityUserPool(forKey: "AWS USERPOOLのキー")
        // 認証する
        let user: AWSCognitoIdentityUser = pool!.getUser(email)
        user.getSession(email, password: password, validationData: nil).continueWith(block: {task in
            if task.error != nil {
                dLog("ログイン失敗:" + task.error.debugDescription)
            } else {
                dLog("ログイン成功")                
                
                // ユーザープールをプロバイダーに設定する
                self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APNortheast1,
                                                                        identityPoolId: "AWS IDENTITY_POOLのID",
                                                                        unauthRoleArn: "AWS UNAUTH_ROLE_ARN",
                                                                        authRoleArn: "AWS AUTH_ROLE_ARN",
                                                                        identityProviderManager: self.pool)
                
                let configuration = AWSServiceConfiguration(region: .APNortheast1,
                                                            credentialsProvider: self.credentialsProvider)
                AWSServiceManager.default().defaultServiceConfiguration = configuration
                
                // IdentityIdを取得する
                self.credentialsProvider?.getIdentityId().continueWith { (task: AWSTask) -> AnyObject? in
                    if (task.error != nil) {
                        
                        dLog("error on login=\(task.error.debugDescription)")
                        
                    } else {
                        if let cognitoId = self.credentialsProvider?.identityId {
                            
                            dLog("Cognito id: \(cognitoId)")
                            
                        } else {
                            dLog("ログイン失敗: Cognito id: nil")
                        }
                    }
                    
                    return nil
                }
            }
            return nil
        })

ログアウトも必要ですね

let pool = AWSCognitoIdentityUserPool(forKey: "AWS USERPOOLのキー")
let user: AWSCognitoIdentityUser = pool.currentUser()!
user.signOut()
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .APNortheast1,
                                                             identityPoolId: "AWS IDENTITY_POOLのID",
                                                             unauthRoleArn: "AWS UNAUTH_ROLE_ARN",
                                                             authRoleArn: "AWS AUTH_ROLE_ARN",
                                                             identityProviderManager: pool)
credentialsProvider.invalidateCachedTemporaryCredentials()
credentialsProvider.clearCredentials()
credentialsProvider.clearKeychain()
pool.clearLastKnownUser()

ハマった点

ここの値が異なっててハマったので次はハマらないぞ。

認証プロバイダー 
 |- Cognitoタブ 
  |-- ユーザープール ID
  |-- アプリクライアント ID
自己紹介
メガネは売っていません
高浜 一道(たかはま かずみち)
大阪でiOSアプリの道を歩くフリーランス。
iPad・iPhoneとサーバを連携した、JSONやDBといったキーワードが出てくるツール系が多めです。
お仕事のご依頼やご連絡はこちらから。
お仕事ください!
Web : ROADTO
ML : k-takahama(a)roadto.jp

個人的なアカウントはこちら。
Tw : @hitonomichi
Fb : kazumichi.takahama