LoginSignup
35
35

More than 5 years have passed since last update.

Swift から AWS Cognito User Pools を使ってみた

Posted at

Cognito に新機能 User Pools が追加されたので、Swift から使ってみました。

やったことは下記の通りです。

  • Cognito User Pools の設定
  • Swift 側の初期設定
  • Sign-up実装
  • ログイン実装

クラスメソッドさんのブログにObjective-C版があったので、参考にさせていただきました。

Cognito User Pools の設定

「Manage your User Pools」を選択し、「Create a User Pool」を選択

スクリーンショット 2016-04-26 23.18.05.png

「Pool name」に任意の名前を入力し、「Step through settings」を選択

スクリーンショット 2016-04-26 23.20.31.png

ユーザごとに取得する属性を選択

私は、email と name を選びました。

スクリーンショット 2016-04-26 23.22.35.png

パスワードポリシーを決定

スクリーンショット 2016-04-26 23.25.12.png

他要素認証とメールやSMSのVerifyをするか

私の場合は、メールアドレスを取得しているので、メールののVeryfyのみオンにしました。

スクリーンショット 2016-04-26 23.26.18.png

アプリを登録

Swift から使用するには、アプリを登録する必要があります。
「Add an app」を選択し、適当なアプリ名を入れてください

スクリーンショット 2016-04-26 23.29.57.png

トリガーからのLambda起動

ログイン時やユーザ作成時などにLambdaを起動できます。
ログをDynamoに挿入したりできて便利そうですが、今回は利用しないのでそのまま「Next step」を押してください。
最後に「Create pool」を選択してください。

Swift 側の初期設定

Pod インストール

Cognito 関連のライブラリをインストールする必要があります。

Podfile
platform :ios, '8.0'

pod 'AWSCore'
pod 'AWSCognitoIdentityProvider'
vi Podfile
pod install

Bridging-Header の追加

下記のファイルを作成し、

CognitoUserpoolSample-Bridging-Header.h
#import <AWSCore/AWSCore.h>
#import <AWSCognitoIdentityProvider.h>

Build Settings > Swift Conpiler - Code Generation > Objective-C Bridging Header に上のファイルを指定する。

"$(SRCROOT)/$(PROJECT)/CognitoUSerpoolSample-Bridging-Header.h"

Sign-up実装

まず、Appdelegate.swift で Pool の初期化を行います。

AppDelegate.swift
let configuration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

let userPoolConfigration: AWSCognitoIdentityUserPoolConfiguration =
    AWSCognitoIdentityUserPoolConfiguration(clientId: "***1", clientSecret: "***2", poolId: "***3")

// 名前をつけておくことで、このプールのインスタンスを取得することができます
AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithUserPoolConfiguration(userPoolConfigration, forKey: "AmazonCognitoIdentityProvider")

ClientId と clientSecret は Apps タブから、

スクリーンショット 2016-04-26 23.47.22.png

poolId は Pool details から確認できます。

スクリーンショット 2016-04-26 23.44.48.png

ユーザ作成部分は、下記のように実装しています。
エラーハンドリングなどはちゃんとできていないです。

var pool: AWSCognitoIdentityUserPool?

override func viewDidLoad() {
    super.viewDidLoad()

    pool = AWSCognitoIdentityUserPool(forKey: "AmazonCognitoIdentityProvider")
}

@IBAction func pushed(sender: AnyObject) {
    let email: AWSCognitoIdentityUserAttributeType = AWSCognitoIdentityUserAttributeType()
    email.name = "email"
    email.value = self.mail.text!

    pool!.signUp(self.name.text!, password: self.password.text!, userAttributes: [email], validationData: nil).continueWithBlock({ task in
        if((task.error) != nil) {
            print(task.error?.code)
        } else {
            print("OK")
        }
        return nil
    })
}

ログイン実装

@IBAction func login(sender: AnyObject) {
    let user: AWSCognitoIdentityUser = pool!.getUser(self.userName.text!)

    user.getSession(self.userName.text!, password: self.password.text!, validationData: nil, scopes: nil).continueWithBlock({task in
        if((task.error) != nil) {
            print(task.error)
        } else {
            print("OK")
        }
        return nil
    })
}

ログインの前に、ユーザのVerifyをしないとエラーになります。
Verify部分は作っていないので、マネージドコンソールから有効化してしまいました。

まとめ

User Pools 非常に便利ですね!
次はLambda連携部分を触ってみたいと思います。

35
35
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
35
35