NextAuth:无法重定向到新用户页面

问题描述 投票:0回答:1

我无法弄清楚为什么当用户使用 CredentialsProvider 登录时没有重定向到 NewUser 页面。对于新用户,授权函数肯定会返回“isNewUser”标志为 true。

参见下面的配置:

import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";

export const authOptions = {
  providers: [
    CredentialsProvider({
      id: "magic-link",
      name: "Magic Link",
      credentials: {
        token: {
          label: "Token",
          type: "text",
          placeholder: "Paste your magic link token here",
        },
      },
      authorize: async (credentials) => {
        try {
          // Validate the token with the backend
          const response = await axios.get(
            `http://localhost:3001/auth/magic-link?token=${credentials.token}`
          );
          const { user, backendTokens, isNewUser } = response.data;


          return { ...user, backendTokens, isNewUser };
        } catch (error) {
          console.error("Error validating magic link:", error);
          return null;
        }
      },
    }),
    CredentialsProvider({
      id: "google",
      name: "Google",
      credentials: {
        query: { label: "Query", type: "text" },
      },
      authorize: async (credentials) => {
        try {
          // Forward the entire query string to the backend
          const response = await axios.get(
            `http://localhost:3001/auth/google/callback?${credentials.query}`
          );
          const { user, backendTokens, isNewUser, expiresIn } = response.data;
          console.log("Magic link response", {
            user,
            backendTokens,
            isNewUser,
            expiresIn,
          });

          return { ...user, backendTokens, isNewUser };
        } catch (error) {
          console.error("Error during Google authentication:", error);
          return null;
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      console.log("JWT callback", { token, user });
      // Check if this is the first time the JWT callback is called (user is defined)
      if (user) {
        token.user = user;
        if (user.backendTokens) {
          token.accessToken = user.backendTokens.accessToken;
          token.refreshToken = user.backendTokens.refreshToken;
        }
      }
      return token;
    },
    async session({ session, token }) {
      console.log("Session callback", { session, token });
      session.user = token.user;
      session.accessToken = token.accessToken;
      session.refreshToken = token.refreshToken;
      return session;
    },
    async redirect({ url, baseUrl }) {
      console.log("Redirect callback", { url, baseUrl });
      // Check if the URL is a callback URL
      if (url.startsWith(baseUrl)) {
        return baseUrl;
      }
      return url;
    },
  },
  pages: {
    signIn: "/auth/signin",
    newUser: "/auth/new-user",
  },
};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

重定向永远不会转到/auth/new-user。它总是直接转到“/”。我该如何解决这个问题?

这是我的 /auth/magic-link 端点,魔术链接指向该端点。我有凭据提供程序,因为我使用 NestJS 后端来发送电子邮件、生成令牌、身份验证等。

authentication next.js nest next-auth
1个回答
0
投票

您是否指定了回调网址?

signIn("credentials", {
  //...
  callbackUrl: `/auth/new-user`
})

或者您可以有条件地重定向用户

import type { SignInResponse } from "next-auth/lib/client"
import { signIn } from "next-auth/react"

import { useRouter } from "next/navigation"

const Page = () => {
  const router = useRouter()

  const onSignInHandler = () => {
    signIn("credentials", {
      //..
      redirect: false,
    })
    .then((res: SignInResponse | undefined) => {
      if (!res.ok)
        alert("Something went wrong!")
      else (res.ok)
        router.push("/auth/new-user")
    })
  }

  return (
    <>
    </>
  )
}

了解更多信息https://next-auth.js.org/getting-started/client#specifying-a-callbackurl

© www.soinside.com 2019 - 2024. All rights reserved.