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

> Lock.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) + "*****マスク済み*****";
          }
          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 <Tooltip tip="パスワードレス: 第1要素としてパスワードに依存しない認証形式。" cta="用語集を表示" href="/ja/docs/glossary?term=Passwordless">パスワードレス</Tooltip> では、WhatsApp の認証方法と同様に、ユーザーにワンタイムパスワードを記載したメールまたは SMS を送信し、ユーザーがそのパスワードを入力して確認することで認証を行います。この記事では、`Lock.Android` ライブラリを使用して code を送信する方法を説明します。

同様の結果は、[ユーザーがクリックできるリンクを送信する](/ja/docs/libraries/lock-android/lock-android-passwordless-with-magic-link)ことで、パスワードレス認証を自動的に完了させる方法でも実現できますが、追加の設定手順がいくつか必要です。

ユーザーを認証できるようにするには、アプリケーションで Email/SMS 接続を有効にし、[Auth0 Dashboard](https://manage.auth0.com/#/connections/passwordless) で設定しておく必要があります。

<div id="implementing-code-passwordless">
  ## Code パスワードレスの実装
</div>

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

`app/build.gradle` ファイルに、Auth0 ドメインおよび Auth0 スキームのプロパティ用の [Manifest Placeholders](https://developer.android.com/studio/build/manifest-build-variables.html) を追加します。これらは、認証結果を受け取る intent-filter を登録するために、ライブラリ内部で使用されます。

```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 を呼び出すアクティビティで、アプリケーション情報を使って `Auth0` のインスタンスを作成します。最も簡単なのは、Android の Context を渡して作成する方法です。これにより、`strings.xml` ファイルであらかじめ定義した値が使用されます。これを有効にするには、文字列リソースを上記の一覧と同じキーで定義する必要があります。

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

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

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

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

Builder クラスを使用して新しい Lock インスタンスを設定します。アカウントの詳細と、前述のコールバック実装を指定します。<Tooltip tip="対象者: 発行されたトークンの対象者を一意に識別する値です。トークン内では aud という名前で表され、その値には IDトークン の場合はアプリケーションの ID（クライアントID）、アクセストークン の場合は API（API Identifier）の ID が含まれます。" cta="用語集を表示" href="/ja/docs/glossary?term=audience">オーディエンス</Tooltip>、スコープ、利用可能な接続などの値もここで設定できます。設定が完了したら、Lock インスタンスをビルドします。このインスタンスは再利用することを前提としているため、不要になったら破棄する必要があります。これを行う適切な場所は、アクティビティの `onDestroy` メソッドです。

以下のサンプルでは、`useCode()` メソッドを呼び出して、ユーザーのメールアドレスまたは電話番号に **code** を送信するよう Lock を設定しています。

```kotlin lines expandable theme={null}
// このアクティビティはパスワードレス Lock を表示します
class MyActivity : AppCompatActivity() {

    private lateinit var lock: PasswordlessLock

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

        val account = Auth0(this)
        // Lock を一度インスタンス化する
        lock = PasswordlessLock.newBuilder(account, callback)
            .useCode()
            // 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) {
            // 例外が発生しました
        }
    }
}
```

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

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

有効になっているパスワードレス接続に応じて、Lock は **code** をメールまたは SMS で送信します。利用可能な場合は、最初に 'email' 接続が選択されます。次に、ユーザーは確認ステップで code を入力する必要があります。その値がサーバーで想定されている値と一致すれば、認証は成功します。
