> ## Documentation Index
> Fetch the complete documentation index at: https://docs-dev-docs-event-stream-action-templates.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) + "*****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 <Tooltip data-tooltip-id="react-containers-DefinitionTooltip-0" href="/docs/ja-jp/glossary?term=passwordless" tip="パスワードレス: 最初の要素としてパスワードに依存しない認証の形式。" cta="用語集の表示">Passwordless</Tooltip>は、WhatsAppの認証方法と同様に、ユーザーがログインするために入力して確認する必要があるワンタイムパスワードを記載したメールまたはSMSをユーザーに送信して認証します。この記事では、`Lock.Android`ライブラリを使用してコードを送信する方法について説明します。

ユーザーがパスワードレス認証を自動的に終了できる[リンクをクリックして送信](/docs/ja-jp/libraries/lock-android/lock-android-passwordless-with-magic-link)することで同様の結果を得ることができますが、さらにいくつかの構成手順が必要になります。

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

## Code Passwordlessの実装

### SDKの構成

`app/build.gradle`ファイルで、Auth0ドメインおよびAuth0スキームプロパティに[マニフェストファイル](https://developer.android.com/studio/build/manifest-build-variables.html)を追加すると、それがライブラリによって内部で使用され、認証結果を取り込むインテントフィルタを登録します。

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

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

        // ---> Add the next line
        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" />

### SDKの使用方法

Lockを起動する予定のアクティビティで、アプリケーションの情報を用いて`Auth0`のインスタンスを作成します。最も簡単な作成方法は、AndroidのContextを渡す方法です。これは、`strings.xml`ファイルで以前定義した値を使用します。これを行うには、文字列リソースが上記のものと同じキーを使用して定義されなければなりません。

```kotlin 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) {
        // Authenticated
    }

    override fun onError(error: AuthenticationException) {
        // Exception occurred
    }
}
```

Builderクラスを使用して構成し、新しいLockインスタンスを準備します。アカウントの詳細と上記で宣言したCallback実装を提供します。オーディエンス、スコープ、使用可能な接続などの値はここで構成できます。完了したら、Lockインスタンスをビルドします。このインスタンスは、再使用されるように意図されており、必要なくなった時に廃棄されなければなりません。これを行うのに最適な場所は、アクティビティの`onDestroy`メソッド内です。

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

```kotlin lines theme={null}
// This activity will show Passwordless Lock
class MyActivity : AppCompatActivity() {

    private lateinit var lock: PasswordlessLock

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

        val account = Auth0(this)
        // Instantiate Lock once
        lock = PasswordlessLock.newBuilder(account, callback)
            .useCode()
            // Customize Lock
            .build(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // Important! Release Lock and its resources
        lock.onDestroy(this)
    }

    private val callback = object : AuthenticationCallback() {
        override fun onAuthentication(credentials: Credentials) {
            // Authenticated
        }

        override fun onError(error: AuthenticationException) {
            // An exception occurred
        }
    }
}
```

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

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

どのパスワードレス接続が有効になっているかに応じて、Lockは**CODE** をメールまたはSMSで送信します。使用可能な場合は、最初に「メール」接続が選択されます。次に、ユーザーは確認手順でCODEを入力する必要があります。値がサーバーが期待するものと等しい場合、認証は成功します。
