You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Clerk实现重置密码后禁用自动登录功能

阻止Clerk重置密码后自动登录的解决方案

我在Next.js项目中使用Clerk实现「忘记密码」功能页面,严格遵循官方文档开发,但遇到一个问题:用户成功重置密码后会自动登录。请问如何阻止该自动登录行为?

以下是我的实现代码:

import React, { SyntheticEvent, useState } from 'react';
import { useSignIn } from '@clerk/nextjs';
import type { NextPage } from 'next';
 
const SignInPage: NextPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [code, setCode] = useState('');
  const [successfulCreation, setSuccessfulCreation] = useState(false);
  const [complete, setComplete] = useState(false);
  const [secondFactor, setSecondFactor] = useState(false);
 
  const { isLoaded, signIn, setActive } = useSignIn();
 
  if (!isLoaded) {
    return null;
  }
 
  async function create(e: SyntheticEvent) {
    e.preventDefault();
    await signIn
      ?.create({
        strategy: 'reset_password_email_code',
        identifier: email,
      })
      .then(_ => {
        setSuccessfulCreation(true);
      })
      .catch(err => console.error('error', err.errors[0].longMessage));
  }
 
  async function reset(e: SyntheticEvent) {
    e.preventDefault();
    await signIn
      ?.attemptFirstFactor({
        strategy: 'reset_password_email_code',
        code,
        password,
      })
      .then(result => {
        if (result.status === 'needs_second_factor') {
          setSecondFactor(true);
        } else if (result.status === 'complete') {
          setActive({ session: result.createdSessionId });
          setComplete(true);
        } else {
          console.log(result);
        }
      })
      .catch(err => console.error('error', err.errors[0].longMessage));
  }
 
  return (
    <div
      style={{
        margin: 'auto',
        maxWidth: '500px',
      }}
    >
      <h1>Forgot Password ?</h1>
      <form
        style={{
          display: 'flex',
          flexDirection: 'column',
          gap: '1em',
        }}
        onSubmit={!successfulCreation ? create : reset}
      >
        {!successfulCreation && !complete && (
          <>
            <label htmlFor='email'>Please provide identifier</label>
            <input
              type='email'
              placeholder='e.g john@doe.com'
              value={email}
              onChange={e => setEmail(e.target.value)}
            />
 
            <button>Sign in</button>
          </>
        )}
 
        {successfulCreation && !complete && (
          <>
            <label htmlFor='password'>New password</label>
            <input
              type='password'
              value={password}
              onChange={e => setPassword(e.target.value)}
            />
 
            <label htmlFor='password'>Reset password code</label>
            <input
              type='text'
              value={code}
              onChange={e => setCode(e.target.value)}
            />
 
            <button>Reset</button>
          </>
        )}
 
        {complete && 'You successfully changed you password'}
        {secondFactor && '2FA is required, this UI does not handle that'}
      </form>
    </div>
  );
};
 
export default SignInPage;

解决方案

问题的核心在于你调用了setActive({ session: result.createdSessionId })——这是Clerk用来激活新会话、触发自动登录的关键代码。要阻止自动登录,直接移除这行代码即可。

修改后的reset函数如下:

async function reset(e: SyntheticEvent) {
  e.preventDefault();
  await signIn
    ?.attemptFirstFactor({
      strategy: 'reset_password_email_code',
      code,
      password,
    })
    .then(result => {
      if (result.status === 'needs_second_factor') {
        setSecondFactor(true);
      } else if (result.status === 'complete') {
        // 移除setActive调用,只标记重置完成
        setComplete(true);
      } else {
        console.log(result);
      }
    })
    .catch(err => console.error('error', err.errors[0].longMessage));
}

移除setActive后,Clerk只会完成密码重置操作,不会自动登录用户。用户需要后续通过登录页面手动重新登录。

内容的提问来源于stack exchange,提问作者Sunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:07:15