> ## 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.

> Native Android アプリ向けに、シームレスなログインとサインアップ体験を提供するウィジェット、Lock for Android の利用を開始しましょう。

# Lock.Android: はじめに

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Lock for Android は Android ネイティブアプリに組み込むことができ、アプリでユーザーのログインやサインアップをスマートに実現できます。Facebook、Google、X などの<Tooltip tip="IDプロバイダー（IdP）: デジタルアイデンティティを保存および管理するサービス。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=identity+providers">アイデンティティプロバイダー</Tooltip>に加え、Active Directory などのエンタープライズプロバイダーにも対応しています。

GitHub の [Lock.Android リポジトリ](https://github.com/auth0/Lock.Android) をご覧ください。

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

[Auth0.Android library](https://github.com/auth0/Auth0.Android) を介して Lock の UI または独自の UI を使用するには、Android API レベル 21 以上、Java バージョン 8 以上が必要です。また、"Native" タイプの Auth0 アプリケーションも必要です。

Android プラグインと Kotlin プラグインでそれぞれ Java 8 のバイトコードをターゲットにするために `build.gradle` に必要な設定は次のとおりです。

```kotlin lines theme={null}
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
```

<div id="installation">
  ## インストール
</div>

Lock は [Maven Central](https://central.sonatype.com/) で利用できます。Lock を使い始めるには、`build.gradle` の dependencies に次の行を追加します。

`implementation 'com.auth0.android:lock:3.+'`

最新バージョンは、リポジトリの [Readme](https://github.com/auth0/Lock.Android#install) または [Maven](https://central.sonatype.com/artifact/com.auth0.android/lock) で確認できます。

Gradle の依存関係を追加したら、プロジェクトを Gradle ファイルと同期することを忘れないでください。

<div id="dashboard-settings">
  ## Auth0 Dashboard の設定
</div>

開始する前に、[Auth0 Dashboard](https://manage.auth0.com/#) でいくつかの設定を行う必要があります。

<div id="callback-url">
  ### コールバック URL
</div>

<Tooltip tip="Auth0 Dashboard: サービスを設定するための Auth0 のメイン製品。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> に移動し、アプリケーションの設定を開きます。次の URL をアプリケーションの **Allowed Callback URLs** に追加します。

`https://{yourDomain}/android/{yourAppPackageName}/callback`

`app/build.gradle` ファイルの `applicationId` の値として指定されている、実際のアプリケーションのパッケージ名に `{yourAppPackageName}` を置き換えてください。

<div id="keystores-and-key-hashes">
  ### キーストアとキーハッシュ
</div>

Androidアプリケーションは、デバイスにインストールする前に署名する必要があります。そのため、Android Studio IDE は初回起動時に、開発ビルドの署名に使用するデフォルトの「Android Debug Keystore」を生成します。この[キーストア](https://developer.android.com/studio/publish/app-signing)は、開発者としての識別に使われるため、本番ビルドで使用するものとは異なる場合があります。

Web Authentication 機能 (つまり、ソーシャル接続) を使用する場合、Lock はデフォルトで Android App Links の使用を試みるように設定されます。そのため、Auth0アプリケーションのダッシュボードで追加の設定が必要です。この手順を完了するには、[Android Keystores and Key Hashes Guide](/docs/ja-jp/libraries/auth0-android/android-development-keystores-hashes)を参照してください。

<div id="implementing-lock-social-database-enterprise">
  ## Lock の実装 (Social, Database, Enterprise)
</div>

以下では、Android 向け Classic Lock の実装方法について説明します。Android 向けの <Tooltip tip="パスワードレス: 第1認証要素としてパスワードに依存しない認証方式。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=Passwordless">パスワードレス</Tooltip> Lock の実装については、[Lock.Android: Passwordless](/docs/ja-jp/libraries/lock-android/lock-android-passwordless) を参照してください。

<div id="configuring-the-sdk">
  ### SDK の設定
</div>

`app/build.gradle` ファイルに、Auth0 Domain と Auth0 Scheme のプロパティ用の [Manifest Placeholders](https://developer.android.com/build/manage-manifests) を追加します。これらは、認証結果を受け取る intent-filter を登録するために、library 内部で使用されます。

```kotlin lines theme={null}
plugins {
    id "com.android.application"
    id "kotlin-android"
}

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "com.auth0.samples"
        minSdkVersion 21
        targetSdkVersion 30
        // ...

        // ---> 次の行を追加
        manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "https"]
        // <---
    }
}
```

これらの値は、あとでコードから参照できる文字列リソースとして `strings.xml` ファイルに追加しておくのが一般的です。このガイドでも、その方法に従います。

export const codeExample = `<resources>
    <string name="com_auth0_client_id">{yourClientId}</string>
    <string name="com_auth0_domain">{yourDomain}</string>
</resources>`;

<AuthCodeBlock children={codeExample} language="xml" />

<div id="sdk-usage">
  ### SDK の使用
</div>

Lock を呼び出す Activity で、アプリケーションの情報を使って `Auth0` のインスタンスを作成します。最も簡単なのは、Android のコンテキストを渡して作成する方法です。これにより、あらかじめ `strings.xml` ファイルで定義した値が使用されます。これを機能させるには、文字列リソースを上記の一覧と同じキー名で定義する必要があります。

```text lines theme={null}
val account = Auth0(context)
```

ユーザー認証イベントを処理する `AuthenticationCallback` 実装を定義します。認証が成功した場合に返される `Credentials` オブジェクトには、最終的にアプリケーションまたは API が使用するトークンが含まれます。詳細は、[トークン](/docs/ja-jp/secure/tokens) を参照してください。

```kotlin lines theme={null}
private val callback = object : AuthenticationCallback() {
    override fun onAuthentication(credentials: Credentials) {
        // 認証済み
    }

    override fun onError(error: AuthenticationException) {
        // 例外が発生しました
    }
}
```

Builder class を使って設定し、新しい Lock インスタンスを準備します。アカウントの詳細と、上で宣言したコールバックの実装を指定してください。<Tooltip tip="audience: 発行されたトークンの対象を一意に識別する識別子です。トークン内では aud という名前で表され、その値には、ID トークンの場合はアプリケーション (Client ID)、アクセストークンの場合は API (API 識別子) の ID が含まれます。" cta="用語集を見る" href="/docs/ja-jp/glossary?term=audience">audience</Tooltip>、scope、使用可能な接続 などの値もここで設定できます。

設定が完了したら、Lock インスタンスをビルドします。このインスタンスは再利用することを前提としており、不要になったら破棄する必要があります。これを行うのに適した場所は、アクティビティの `onDestroy` メソッドです。

```kotlin lines expandable theme={null}
// このアクティビティでLockを表示する
class MyActivity : AppCompatActivity() {

    private lateinit var lock: Lock

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val account = Auth0(this)
        // Lockを一度だけインスタンス化する
        lock = Lock.newBuilder(account, callback)
            // Lockをカスタマイズする
            .build(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // 重要！Lockとそのリソースを解放する
        lock.onDestroy(this)
    }

    private val callback = object : AuthenticationCallback() {
        override fun onAuthentication(credentials: Credentials) {
            // 認証済み
        }

        override fun onError(error: AuthenticationException) {
            // 例外が発生しました
        }
    }
}
```

最後に、アクティビティ内で `Lock` ウィジェットを起動します。

```kotlin lines theme={null}
startActivity(lock.newIntent(this))
```

これで完了です！あとはLockが処理してくれます。

<div id="android-app-links-custom-scheme">
  #### Android App Links - カスタムスキーム
</div>

この記事および Lock のデフォルトで使用されるコールバック URI スキームは `https` です。[Android App Links](https://developer.android.com/training/app-links) を使用している場合、これは Android Marshmallow (API 23) 以降で最も適切に動作しますが、それ以前の Android バージョンでは、インテントの処理先としてアプリケーションとブラウザーのどちらを使うかをユーザーに選択させるインテントチューザー ダイアログが表示されることがあります。これは「曖昧性解消ダイアログ」と呼ばれます。OS がリンクを直接アプリで開くようにするには、一意のカスタムスキームを使用してこの動作を変更できます。

1. `app/build.gradle` ファイル内の `auth0Scheme` Manifest Placeholder の値、または `AndroidManifest.xml` ファイル内の Intent Filter 定義を直接更新し、既存のスキームを新しいものに変更します。
2. Auth0 Dashboard のアプリケーションの設定にある "Allowed Callback URLs" を、新しいスキームで始まる URL と一致するように更新します。
3. ビルダーで Lock を設定する際に `withScheme()` を呼び出し、使用するスキームを渡します。

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  スキームの値は、すべて小文字である必要があります。そうでない場合は警告メッセージがログに記録され、authentication は完了しません。
</Callout>

<div id="lock-configuration">
  ## Lock の設定
</div>

Lock の設定オプションの一覧については、[Lock.Android: 設定](/docs/ja-jp/libraries/lock-android/lock-android-configuration)をご覧ください。

<div id="error-messages">
  ## エラーメッセージ
</div>

コールバックで `AuthenticationException` を受け取った場合は、各エラーケースの見分け方について [ソース](https://github.com/auth0/Auth0.Android/blob/main/auth0/src/main/java/com/auth0/android/authentication/AuthenticationException.kt) を確認してください。

<div id="learn-more">
  ## 詳しくはこちら
</div>

* [Lock.Android: カスタムテーマ](/docs/ja-jp/libraries/lock-android/lock-android-custom-theming)
* [Lock.Android: 設定](/docs/ja-jp/libraries/lock-android/lock-android-configuration)
* [Lock.Android: サインアップ時のカスタムフィールド](/docs/ja-jp/libraries/lock-android/lock-android-custom-fields-at-signup)
* [Lock.Androidの国際化](/docs/ja-jp/customize/internationalization-and-localization/lock-android-internationalization)
* [ログアウト](/docs/ja-jp/authenticate/login/logout)
