> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Guardian.swift iOS SDK のインストール方法、使用方法、設定オプションについて説明します。

# Guardian.swift iOS SDK

[Guardian.swift](https://github.com/auth0/Guardian.swift) を使用すると、Auth0 の Guardian 多要素認証サービスを独自の iOS アプリに統合し、アプリ自体を第二の認証要素として機能させることができます。これにより、ユーザーはアプリからシームレスな <Tooltip tip="多要素認証 (MFA): SMS 経由のコードなど、ユーザー名とパスワードに加えた認証要素を使用するユーザー認証プロセス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=multi-factor+authentication">多要素認証</Tooltip> のメリットをすべて利用できます。詳しくは、[Apple Push Notification Service の利用を開始する](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-push-notifications-for-mfa#configure-push-notifications-for-apple-using-apn-) をご覧ください。

<div id="requirements">
  ## 要件
</div>

* Guardianを使用するには、iOS 10以降とSwift 4.1が必要です。
* このSDKを使用するには、テナントのGuardianサービスに独自のプッシュ通知用資格情報を設定する必要があります。設定しないと、プッシュ通知を受信できません。詳しくは、[MFAのプッシュ通知を設定する](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-push-notifications-for-mfa)をご覧ください。

<div id="install-guardian-ios-sdk">
  ## Guardian iOS SDK のインストール
</div>

<div id="cocoapods">
  ### CocoaPods
</div>

Guardian.swift は [CocoaPods](http://cocoapods.org) から利用できます。インストールするには、Podfile に次の行を追加してください。

```bash lines theme={null}
pod 'Guardian', '~> 1.1.0'
```

<div id="carthage">
  ### Carthage
</div>

Cartfile に次の行を追加します。

```bash lines theme={null}
github "auth0/Guardian.swift" ~> 1.1.0
```

<div id="enable-guardian-push-notifications">
  ## Guardianのプッシュ通知を有効にする
</div>

1. [Auth0 Dashboard > セキュリティ > Multi-factor Auth](https://manage.auth0.com/#/guardian) に移動します。
2. **Push Notification** をオンにします。
3. [プッシュ通知を設定する](/docs/ja-jp/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-push-notifications-for-mfa#configure-push-notifications-for-apple-using-apn-)。

<div id="usage">
  ## 使用状況
</div>

`Guardian` は SDK の中核となるコンポーネントです。SDK を利用するには、ライブラリをインポートします：

```swift lines theme={null}
import Guardian
```

テナントのドメインを設定します。テナント用に設定している場合は、<Tooltip tip="カスタムドメイン: 固有名またはバニティ名を使用するサードパーティのドメイン。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=custom+domain">カスタムドメイン</Tooltip> を使用することもできます:

```swift lines theme={null}
let domain = "<tenant>.<region>.auth0.com"
```

<div id="enroll">
  ### 登録
</div>

登録とは、第2認証要素とAuth0アカウントとのリンクです。アカウントを登録すると、アイデンティティの確認に必要な第2認証要素の提示が必要になります。まだアプリでプッシュ通知を使用していない場合や、プッシュ通知にあまりなじみがない場合は、詳しくは [Apple Push Notification Service Overview](https://developer.apple.com/go/?id=push-notifications) を参照してください。

登録には、テナントドメインに加えて、次の情報が必要です。

| Variable           | Description                                                         |
| ------------------ | ------------------------------------------------------------------- |
| **Enrollment URI** | Guardian Web WidgetでスキャンしたQRコード、またはメールやSMSで送信された登録チケットにエンコードされている値。 |
| **APNS Token**     | デバイスのApple APNSトークン。64バイトを含む文字列 (16進形式) である必要があります。                 |
| **Key Pair**       | Auth0 Guardianに対して自身のアイデンティティを証明するために使用するRSA (秘密鍵/公開鍵) のキーペア。       |

情報がそろったら、デバイスを登録できます。

```swift lines theme={null}
Guardian
        .enroll(forDomain: "{yourTenantDomain}",
                usingUri: "{enrollmentUri}",
                notificationToken: "{apnsToken}",
                signingKey: signingKey,
                verificationKey: verificationKey
                )
        .start { result in
            switch result {
            case .success(let enrolledDevice):
                // 成功。登録済みデバイスのデータが利用可能です
            case .failure(let cause):
                // 失敗。causeを確認して原因を調べてください
            }
        }
```

成功すると、登録情報を取得できます。この情報はアプリケーション内に安全に保存する必要があります。この情報には、登録識別子と、登録情報の更新または削除に使用する、デバイスに関連付けられた Guardian API 用のトークンが含まれます。

<div id="signing-and-verification-keys">
  #### 署名鍵と検証用キー
</div>

Guardian.swift では、署名鍵を生成するための便利なクラスが提供されています。

```swift lines theme={null}
let signingKey = try DataRSAPrivateKey.new()
```

このキーはメモリ内にしか存在しませんが、`Data`形式で取得し、たとえば暗号化されたSQLiteDBに安全に保存できます。

```javascript lines theme={null}
// データを保存する
let data = signingKey.data
// 保存処理を実行する

// Storageから読み込む
let loadedKey = try DataRSAPrivateKey(data: data)
```

ただ、iOS Keychain に保存したいだけなら:

```swift wrap lines theme={null}
let signingKey = try KeychainRSAPrivateKey.new(with: "com.myapp.mytag")
```

上記の例では、キーが作成され、指定したタグの下に自動的に保存されます。取得する場合は、そのタグを使用できます。

```swift wrap lines theme={null}
let signingKey = try KeychainRSAPrivateKey(tag: "com.myapp.mytag")
```

検証用のキーは、たとえば任意の `SigningKey` から取得できます。

```swift lines theme={null}
let verificationKey = try signingKey.verificationKey()
```

<div id="allow-login-requests">
  ### ログインリクエストを許可する
</div>

登録が完了すると、ユーザーが MFA で本人確認を行う必要があるたびに、プッシュ通知を受け取ります。Guardian には、APNs から受信したデータを解析し、すぐに使える `Notification` インスタンスを返すメソッドがあります。

```swift lines theme={null}
if let notification = Guardian.notification(from: notificationPayload) {
    // Guardianのプッシュ通知を受信しました
}
```

通知インスタンスを取得したら、`allow` メソッドを使って認証リクエストを簡単に許可できます。また、以前に取得した登録済みデバイスの情報もいくつか必要です。登録情報が複数ある場合は、通知と同じ `id` (`enrollmentId` プロパティ) を持つものを見つける必要があります。

情報がそろったら、`device` パラメータには、プロトコル `AuthenticatedDevice` を実装する任意のオブジェクトを指定できます:

```swift lines theme={null}
struct Authenticator: Guardian.AuthenticationDevice {
    let signingKey: SigningKey
    let localIdentifier: String
}
```

ローカル識別子はデバイスのローカル ID で、登録時にはデフォルトで `UIDevice.current.identifierForVendor` が使われます。あとは次を呼び出すだけです:

```swift lines theme={null}
Guardian
        .authentication(forDomain: "{yourTenantDomain}", device: device)
        .allow(notification: notification)
        .start { result in
            switch result {
            case .success:
                // 認証リクエストが正常に許可されました
            case .failure(let cause):
                // エラーが発生しました。causeを確認して原因を調べてください
            }
        }
```

<div id="reject-login-requests">
  ### ログインリクエストを拒否する
</div>

認証リクエストを拒否するには、代わりに `reject` を呼び出します。必要に応じて、拒否理由を送信することもできます。拒否理由は Guardian のログに表示されます。

```swift lines theme={null}
Guardian
        .authentication(forDomain: "{yourTenantDomain}", device: device)
        .reject(notification: notification)
        // または reject(notification: notification, withReason: "hacked")
        .start { result in
            switch result {
            case .success:
                // 認証リクエストが正常に拒否されました
            case .failure(let cause):
                // エラーが発生しました。causeを確認して原因を調べてください
            }
        }
```

<div id="unenroll">
  ### 登録解除
</div>

たとえば MFA を無効にする場合など、登録を削除するには、次のリクエストを送信します。

```swift lines theme={null}
Guardian
        .api(forDomain: "{yourTenantDomain}")
        .device(forEnrollmentId: "{userEnrollmentId}", token: "{enrollmentDeviceToken}")
        .delete()
        .start { result in
            switch result {
            case .success:
                // 成功、enrollmentが削除されました
            case .failure(let cause):
                // 失敗しました。causeを確認して原因を調べてください
            }
        }
```

<div id="set-up-mobile-only-otp-enrollment">
  ### モバイル専用のOTP登録を設定する
</div>

<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 の主要製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> または <Tooltip tip="Management API: お客様が管理タスクを実行するための製品です。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Management+API">Management API</Tooltip> を使用して、OTPをMFA認証要素として有効にできます。このオプションではQR codeは不要で、ユーザーは手動で登録できます。

ユーザーに登録を案内するには、[Auth0 Dashboard > User Management > Users](https://manage.auth0.com/#/users) に移動してユーザーを選択します。次に、Details タブを開き、Multi-Factor Authentication セクションから登録招待を送信します。

<div id="connect-a-resource">
  #### リソースを接続する
</div>

Auth0 Dashboard または Guardian SDK を使って、リソースを接続できます。

<div id="use-auth0-dashboard">
  ##### Auth0 Dashboard を使用する
</div>

1. Auth0ログインプロンプトにアクセスし、表示されたコード、または別のソースから取得した同様のBase32エンコード済みキーをコピーします。次の手順で、このコードを認証アプリに入力します。

   <Frame>
     <img src="https://mintcdn.com/translations/eVsQcTnbClN-oB7d/docs/images/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/047513dfe1d40a22ce811b131d5ea289/OTP_Challenge_2_-_English.png?fit=max&auto=format&n=eVsQcTnbClN-oB7d&q=85&s=128a02f4c7f65e7a1d82640b1b9842f6" alt="ワンタイムコードが表示されたログインプロンプトの例" width="492" height="679" data-path="docs/images/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/047513dfe1d40a22ce811b131d5ea289/OTP_Challenge_2_-_English.png" />
   </Frame>
2. コピーしたコードを、Guardian などの認証アプリに追加します。

<div id="use-the-sdk">
  ##### SDKを使用する
</div>

1. Guardianライブラリをインポートします。

   ```swift lines theme={null}
   import Guardian
   ```

2. コードジェネレーターを作成します。

   ```swift lines theme={null}
   let codeGenerator = try Guardian.totp(

      base32Secret: enrollmentCode,  // ユーザーが入力した登録コード

      algorithm: .sha1			// TOTPで使用するアルゴリズム

   )
   ```

3. 生成されたコードを取得します。

   ```swift lines theme={null}
   codeGenerator.code()
   ```

<div id="enter-one-time-code">
  #### ワンタイムコードを入力
</div>

Auth0 のログインプロンプトで、前の手順で生成したワンタイムコードを入力します。

<Frame>
  <img src="https://mintcdn.com/translations/eVsQcTnbClN-oB7d/docs/images/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/047513dfe1d40a22ce811b131d5ea289/OTP_Challenge_2_-_English.png?fit=max&auto=format&n=eVsQcTnbClN-oB7d&q=85&s=128a02f4c7f65e7a1d82640b1b9842f6" alt="ワンタイムコードが表示されたログインプロンプトの例" width="492" height="679" data-path="docs/images/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/047513dfe1d40a22ce811b131d5ea289/OTP_Challenge_2_-_English.png" />
</Frame>

Continueを選択すると、アプリケーションがお使いのユーザーの認証要素として追加されたことを示すメッセージが表示されます。

<div id="log-in-with-your-app">
  #### アプリでログインする
</div>

認証要素の登録が完了すると、ユーザーはアプリを使ってログインできるようになります。まず、認証方法として Guardian アプリを選択します。

<Frame>
  <img src="https://mintcdn.com/translations/eVsQcTnbClN-oB7d/docs/images/cdy7uua7fh8z/1k7IsU9kfP5mrXU2jfGHuT/d61e0dcd09b633dbeb2cb54e1fd49018/2025-01-27_14-47-32.png?fit=max&auto=format&n=eVsQcTnbClN-oB7d&q=85&s=8688ecf3a0d42d92a6479adea541793d" alt="認証方法の選択画面" width="396" height="775" data-path="docs/images/cdy7uua7fh8z/1k7IsU9kfP5mrXU2jfGHuT/d61e0dcd09b633dbeb2cb54e1fd49018/2025-01-27_14-47-32.png" />
</Frame>

次に、本人確認のため、ログインプロンプトにワンタイムコードを入力します。

<Frame>
  <img src="https://mintcdn.com/translations/mMSz-RNYLuOm2GmQ/docs/images/cdy7uua7fh8z/S6uTieLjtuNUrQRMh8uch/21f1671d21ae9f61b63154ffaa21b5a2/OTP_Challenge_-_English.png?fit=max&auto=format&n=mMSz-RNYLuOm2GmQ&q=85&s=5db00906087d0b3d46e36cddc464d667" alt="ユーザーにワンタイムコードの入力を求める「Verify Your Identity」画面" width="494" height="669" data-path="docs/images/cdy7uua7fh8z/S6uTieLjtuNUrQRMh8uch/21f1671d21ae9f61b63154ffaa21b5a2/OTP_Challenge_-_English.png" />
</Frame>
