次の方法で共有


チュートリアル: ネイティブ認証 JavaScript SDK を使用して React シングルページ アプリのパスワードをリセットする

適用対象: 次の内容が外部テナントに適用されることを示す白いチェック マーク記号が付いた緑の円。 外部テナント (詳細)

このチュートリアルでは、ネイティブ認証 JavaScript SDK を使用して React シングルページ アプリでパスワードリセットを有効にする方法について説明します。

このチュートリアルでは、次の操作を行います。

  • React アプリを更新して、ユーザーのパスワードをリセットします。
  • パスワード リセット フローをテストする

[前提条件]

UI コンポーネントを作成する

パスワード リセット フロー中に、このアプリはユーザーのユーザー名 (電子メール)、ワンタイム パスコード、新しいユーザー パスワードを異なる画面で収集します。 このセクションでは、アプリがパスワードをリセットするために必要な情報を収集するフォームを作成します。

  1. src/app/reset-password という名前のフォルダーを作成します。

  2. reset-password/components/InitialForm.tsx ファイルを作成し、reset-password/components/InitialForm.tsx のコードを貼り付けます。 このコンポーネントには、ユーザーのユーザー名 (電子メール) を収集するフォームが表示されます。

  3. reset-password/components/CodeForm.tsx ファイルを作成し、reset-password/components/CodeForm.tsx からコードを貼り付けます。 このコンポーネントは、ユーザーが受信したワンタイム パスコードを電子メールの受信トレイに収集するフォームを表示します。

  4. reset-password/components/NewPasswordForm.tsx ファイルを作成し、reset-password/components/NewPasswordForm.tsx のコードを貼り付けます。 このコンポーネントには、ユーザーの新しいパスワードを収集するフォームが表示されます。

フォームの操作を処理する

サインイン フローのロジックを処理する reset-password/page.tsx ファイルを作成します。 このファイルでは、次の操作を行います。

  • 必要なコンポーネントをインポートし、状態に基づいて適切なフォームを表示します。 reset-password/page.tsx の完全な例を参照してください。

    import {
      CustomAuthPublicClientApplication,
      ICustomAuthPublicClientApplication,
      ResetPasswordCodeRequiredState,
      ResetPasswordPasswordRequiredState,
      ResetPasswordCompletedState,
      AuthFlowStateBase,
    } from "@azure/msal-browser/custom-auth";
    
    export default function ResetPassword() {
      const [app, setApp] = useState<ICustomAuthPublicClientApplication | null>(
        null
      );
      const [loadingAccountStatus, setLoadingAccountStatus] = useState(true);
      const [isSignedIn, setSignInState] = useState(false);
      const [email, setEmail] = useState("");
      const [code, setCode] = useState("");
      const [newPassword, setNewPassword] = useState("");
      const [error, setError] = useState("");
      const [loading, setLoading] = useState(false);
      const [resetState, setResetState] = useState<AuthFlowStateBase | null>(
        null
      );
    
      useEffect(() => {
        const initializeApp = async () => {
          const appInstance = await CustomAuthPublicClientApplication.create(
            customAuthConfig
          );
          setApp(appInstance);
        };
    
        initializeApp();
      }, []);
    
      useEffect(() => {
        const checkAccount = async () => {
          if (!app) return;
    
          const accountResult = app.getCurrentAccount();
    
          if (accountResult.isCompleted()) {
            setSignInState(true);
          }
    
          setLoadingAccountStatus(false);
        };
    
        checkAccount();
      }, [app]);
    
      const renderForm = () => {
        if (loadingAccountStatus) {
          return;
        }
    
        if (isSignedIn) {
          return (
            <div style={styles.signed_in_msg}>
              Please sign out before processing the password reset.
            </div>
          );
        }
    
        if (resetState instanceof ResetPasswordPasswordRequiredState) {
          return (
            <NewPasswordForm
              onSubmit={handleNewPasswordSubmit}
              newPassword={newPassword}
              setNewPassword={setNewPassword}
              loading={loading}
            />
          );
        }
    
        if (resetState instanceof ResetPasswordCodeRequiredState) {
          return (
            <CodeForm
              onSubmit={handleCodeSubmit}
              code={code}
              setCode={setCode}
              loading={loading}
            />
          );
        }
    
        if (resetState instanceof ResetPasswordCompletedState) {
          return <ResetPasswordResultPage />;
        }
    
        return (
          <InitialForm
            onSubmit={handleInitialSubmit}
            email={email}
            setEmail={setEmail}
            loading={loading}
          />
        );
      };
    
      return (
        <div style={styles.container}>
          <h2 style={styles.h2}>Reset Password</h2>
          {renderForm()}
          {error && <div style={styles.error}>{error}</div>}
        </div>
      );
    }
    
  • パスワード リセット フローを開始するには、次のコード スニペットを使用します。 コード スニペットを配置する場所については、 reset-password/page.tsx の完全な例を参照してください。

    const handleInitialSubmit = async (e: React.FormEvent) => {
        if (!app) return;
        e.preventDefault();
        setError("");
        setLoading(true);
        const result = await app.resetPassword({
            username: email,
        });
        const state = result.state;
        if (result.isFailed()) {
            if (result.error?.isInvalidUsername()) {
                setError("Invalid email address");
            } else if (result.error?.isUserNotFound()) {
                setError("User not found");
            } else {
                setError(
                    result.error?.errorData.errorDescription || "An error occurred while initiating password reset"
                );
            }
        } else {
            setResetState(state);
        }
        setLoading(false);
    };
    

    SDK のインスタンス メソッド ( resetPassword()) は、パスワード リセット フローを開始します。

  • ワンタイム パスコードを送信するには、次のコード スニペットを使用します。 コード スニペットを配置する場所については、 reset-password/page.tsx の完全な例を参照してください。

    const handleCodeSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError("");
        setLoading(true);
        if (resetState instanceof ResetPasswordCodeRequiredState) {
            const result = await resetState.submitCode(code);
            const state = result.state;
            if (result.isFailed()) {
                if (result.error?.isInvalidCode()) {
                    setError("Invalid verification code");
                } else {
                    setError(result.error?.errorData.errorDescription || "An error occurred while verifying the code");
                }
            } else {
                setResetState(state);
            }
        }
        setLoading(false);
    };
    

    パスワード リセット状態の submitCode() は、ワンタイム パスコードを送信します。

  • ユーザーの新しいパスワードを送信するには、次のコード スニペットを使用します。 コード スニペットを配置する場所については、 reset-password/page.tsx の完全な例を参照してください。

    const handleNewPasswordSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError("");
        setLoading(true);
        if (resetState instanceof ResetPasswordPasswordRequiredState) {
            const result = await resetState.submitNewPassword(newPassword);
            const state = result.state;
            if (result.isFailed()) {
                if (result.error?.isInvalidPassword()) {
                    setError("Invalid password");
                } else {
                    setError(result.error?.errorData.errorDescription || "An error occurred while setting new password");
                }
            } else {
                setResetState(state);
            }
        }
        setLoading(false);
    };
    

    パスワード リセット状態の submitNewPassword() は、ユーザーの新しいパスワードを送信します。

  • パスワードリセットの結果を使用するには、次のコード スニペットを使用します。 コード スニペットを配置する場所については、 reset-password/page.tsx の完全な例を参照してください。

    if (resetState instanceof ResetPasswordCompletedState) {
        return <ResetPasswordResultPage/>;
    }
    
    

省略可能: パスワードのリセット後にユーザーを自動的にサインインする

ユーザーが自分のパスワードを正常にリセットしたら、新しいサインイン フローを開始せずにアプリに直接サインインできます。 これを行うには、次のコード スニペットを使用します。 reset-password/page.tsx の完全な例を参照してください。

if (resetState instanceof ResetPasswordCompletedState) {
    const result = await resetState.signIn();
    const state = result.state;
    if (result.isFailed()) {
        setError(result.error?.errorData?.errorDescription || "An error occurred during auto sign-in");
    }
    if (result.isCompleted()) {
        setData(result.data);
        setResetState(state);
    }
}

アプリを実行してテストする

アプリの実行とテスト 」の手順に従ってアプリを実行し、サインイン フローをテストします。