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

# Guardian.swift iOS SDK

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

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  この機能は廃止されているため、日本語のUIスクリーンショットは利用できません。
</Callout>

## 要件

* 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)」を参照してください。

## Guardian iOS SDKをインストールする

### CocoaPods

Guardian.swiftは[CocoaPods](http://cocoapods.org)から入手可能です。インストールするには、以下の行をPodfileに追加します。

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

### Carthage

以下の行をCartfileに追加します。

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

## Guardianプッシュ通知を有効にする

1. [［Dashboard］ > ［Security（セキュリティ）］ > ［Multi-factor Auth（多要素認証）］](https://manage.auth0.com/#/guardian)に進みます。
2. **［Push Notification（プッシュ通知）］** を切り替えて有効にします。
3. [プッシュ通知を構成します](https://auth0.com/docs/secure/multi-factor-authentication/multi-factor-authentication-factors/configure-push-notifications-for-mfa#configure-push-notifications-for-apple-using-apn-)。

## Usage（使用）

`Guardian`はSDKの中核です。SDKを使用するには、ライブラリをインポートします。

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

テナントのドメインを設定します。または、テナントにカスタムドメインを構成している場合、それを使用します。

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

### 登録

登録は、第二要素とAuth0アカウント間のリンクです。アカウントが登録されると、本人確認に必要な第二要素を提供するためにアカウントが必要になります。アプリがまだプッシュ通知を使用していない場合、またはプッシュ通知に慣れていない場合、「[Appleプッシュ通知サービスの概要](https://developer.apple.com/go/?id=push-notifications)」を参照してください。

登録には、テナントのドメイン以外に以下の情報が必要です。

| 変数                        | 説明                                                                   |
| ------------------------- | -------------------------------------------------------------------- |
| **Enrollment URI（登録URI）** | Guardian WebウィジェットからスキャンしたQRコード、またはメールかSMS経由で送られてきた登録チケットにエンコードされた値。 |
| **APNS Token（APNSトークン）**  | デバイスのApple APNSトークン。64バイト（16進数形式）を含む文字列で指定する必要があります。                 |
| **Key Pair（鍵ペア）**         | Auth0 GuardianでIDをアサ―トするのに使用する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):
                // success, we have the enrollment device data available
            case .failure(let cause):
                // something failed, check cause to see what went wrong
            }
        }
```

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

#### 署名キーと検証キー

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

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

このキーはメモリ内にしか存在しません、`データ`表現を取得し、暗号化されたSQLiteDBなどにセキュアに保存できます。

```swift lines theme={null}
// Store data
let data = signingKey.data
// perform the storage

// Load from Storage
let loadedKey = try DataRSAPrivateKey(data: data)
```

しかし、iOSキーチェーンに保存したいだけなら、以下の手順で可能です。

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

上記の例では、キーを作成し、与えられたタグの下に自動的に保存します。それを取得したい場合、タグを使用できます。

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

検証キーは、`SigningKey`から取得できます。以下の例を挙げます。

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

### ログイン要求を許可する

登録を行うと、<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=multifactor-authentication" tip="多要素認証（MFA）: ユーザー名とパスワードに加えて、SMS経由のコードなどの要素を使用するユーザー認証プロセス。" cta="用語集の表示">MFA</Tooltip>で本人確認が必要になるたびにプッシュ通知が届きます。Guardianは、APNから受信したデータを解析し、使用可能な`Notification`インスタンスを返すメソッドを提供します。

```swift lines theme={null}
if let notification = Guardian.notification(from: notificationPayload) {
    // we have received a Guardian push notification
}
```

通知インスタンスを取得すると、`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:
                // the auth request was successfuly allowed
            case .failure(let cause):
                // something failed, check cause to see what went wrong
            }
        }
```

### ログイン要求を拒否する

認証要求を拒否するには、代わりに`reject`を呼び出します。オプションで拒否の理由を送ることもできます。拒否の理由はGuardianログに表示されます。

```swift lines theme={null}
Guardian
        .authentication(forDomain: "{yourTenantDomain}", device: device)
        .reject(notification: notification)
        // or reject(notification: notification, withReason: "hacked")
        .start { result in
            switch result {
            case .success:
                // the auth request was successfuly rejected
            case .failure(let cause):
                // something failed, check cause to see what went wrong
            }
        }
```

### 登録解除する

登録を削除したい場合、たとえばMFAを無効にしたい場合は、以下の要求を行います。

```swift lines theme={null}
Guardian
        .api(forDomain: "{yourTenantDomain}")
        .device(forEnrollmentId: "{userEnrollmentId}", token: "{enrollmentDeviceToken}")
        .delete()
        .start { result in
            switch result {
            case .success:
                // success, the enrollment was deleted
            case .failure(let cause):
                // something failed, check cause to see what went wrong
            }
        }
```

### モバイル専用OTP登録をセットアップする

<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=auth0-dashboard" tip="Auth0 Dashboard: サービスを構成するためのAuth0の主製品。" cta="用語集の表示">Auth0 Dashboard</Tooltip>または<Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=management-api" tip="Management API: 顧客が管理タスクを実行できるようにするための製品。" cta="用語集の表示">Management API</Tooltip>を使用して、MFA要素としてワンタイムパスワード（OTP）を有効にすることができます。このオプションにはQRコードは必要なく、ユーザーが手動で登録できます。

ユーザーを登録に招待するには、[Auth0 Dashboard > ［User Management（ユーザー管理）］ > ［Users（ユーザー）］](https://manage.auth0.com/#/users)に進み、ユーザーを選択します。その後、［Details（詳細）］タブにアクセスし、［Multi-Factor Authentication（多要素認証）］セクションを使用して登録招待を送信します。

#### リソースを接続する

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

##### Auth0 Dashboardの使用

1. Auth0ログインプロンプトにアクセスし、提供されたコード、または別のソースから取得した同様のbase32エンコードキーをコピーします。次のステップでは、このコードを認証アプリケーションに入力します。

   <Frame>
     <img src="https://mintcdn.com/docs-dev-fix-docs-5525/vwc6ytjRt-BhgDpL/docs/images/ja-jp/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/24838237a74ae47d42a23a059edad27a/OTP_Challenge_2_-_Japanese.png?fit=max&auto=format&n=vwc6ytjRt-BhgDpL&q=85&s=76b82deb327756399aae3fb436c39997" alt="An example login prompt displaying a one-time code" width="492" height="680" data-path="docs/images/ja-jp/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/24838237a74ae47d42a23a059edad27a/OTP_Challenge_2_-_Japanese.png" />
   </Frame>

2. コピーしたコードをGuardianなどの認証アプリケーションに追加します。

##### SDKを使用する

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

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

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

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

      base32Secret: enrollmentCode,  // Enrollment code entered by user

      algorithm: .sha1			// Algorithm used by TOTP

   )
   ```

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

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

#### ワンタイムコードを入力する

Auth0ログインプロンプトで、前のステップで生成したコードを入力します。

<Frame>
  <img src="https://mintcdn.com/docs-dev-fix-docs-5525/vwc6ytjRt-BhgDpL/docs/images/ja-jp/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/24838237a74ae47d42a23a059edad27a/OTP_Challenge_2_-_Japanese.png?fit=max&auto=format&n=vwc6ytjRt-BhgDpL&q=85&s=76b82deb327756399aae3fb436c39997" alt="An example login prompt displaying a one-time code" width="492" height="680" data-path="docs/images/ja-jp/cdy7uua7fh8z/1yoqiIuERVTwCU8yfx6IM8/24838237a74ae47d42a23a059edad27a/OTP_Challenge_2_-_Japanese.png" />
</Frame>

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

#### アプリでログインする

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

<Frame>
  <img src="https://mintcdn.com/docs-dev-fix-docs-5525/vwc6ytjRt-BhgDpL/docs/images/ja-jp/cdy7uua7fh8z/1k7IsU9kfP5mrXU2jfGHuT/2ab98043294c662bd8b165eb04df9aa1/2025-01-27_14-46-27.png?fit=max&auto=format&n=vwc6ytjRt-BhgDpL&q=85&s=eead360d4c5a47b1cea855c2375a8f71" alt="The authentication method selection screen" width="392" height="817" data-path="docs/images/ja-jp/cdy7uua7fh8z/1k7IsU9kfP5mrXU2jfGHuT/2ab98043294c662bd8b165eb04df9aa1/2025-01-27_14-46-27.png" />
</Frame>

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

<Frame>
  <img src="https://mintcdn.com/docs-dev-fix-docs-5525/nyn7PO6A36QuMyn8/docs/images/ja-jp/cdy7uua7fh8z/S6uTieLjtuNUrQRMh8uch/21156d1cdf4b839d73ba97b1c149c77b/OTP_Challenge_-_Japanese.png?fit=max&auto=format&n=nyn7PO6A36QuMyn8&q=85&s=208ac68881686dfb709adf97fb0ce687" alt="The Verify Your Identity screen prompting the user for a one-time code" width="494" height="660" data-path="docs/images/ja-jp/cdy7uua7fh8z/S6uTieLjtuNUrQRMh8uch/21156d1cdf4b839d73ba97b1c149c77b/OTP_Challenge_-_Japanese.png" />
</Frame>
