使用 nextjs-auth0 在 afterCallback 中重定向

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

我正在使用 Nextjs 14 应用程序路由器、Auth0 和 next-auth0,下面的代码片段来自

/app/api/auth/[auth0]/route.ts
中的文件。

我有多种情况需要根据用户令牌中的多个字段和自定义声明来处理重定向用户(它有点复杂的 if/else 块)

采用第一个也是更简单的示例,如果

/email-verification
为 false,则将用户重定向到
user.email_verified

const afterCallback = async (req: any, session: any, state: any) => {
      const res = new NextResponse()
      if (session.user) {
            // check email
            if (!session.user.email_verified) {
                  // redirect("/auth/email-verification", RedirectType.replace)
                 return NextResponse.redirect(
                      new URL("/auth/email-verification", req.url),
                      res
                  )
      } else {
            // MULTI LEVELS IF-ELSE BLOCKS WITH REDIRECTION
      }
      return session

export const GET = handleAuth({
    callback: async (req: any, res: any) => {
        try {
            return await handleCallback(req, res, {
                afterCallback,
            })
        } catch (error) {
            console.error(error)
        }
    },
})

我总是收到以下错误(使用重定向或返回 NextResponse)

代码:'ERR_CALLBACK_HANDLER_FAILURE', 原因:错误:NEXT_REDIRECT

next.js auth0 next.js13
1个回答
0
投票

根据Auth0 SDK文档。另外,我可以补充一点,根据我的经验,

afterCallback
处理程序不支持后退导航。因此,最好将 try-catch 保留在您自己的代码中,并在出现错误时重定向。否则,您的用户在返回导航时将遇到空白屏幕或错误消息。

// app/api/auth/[auth0]/route.js
import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
import { redirect } from 'next/navigation';

const afterCallback = (req, session, state) => {
  if (session.user.isAdmin) {
    return session;
  } else {
    redirect('/unauthorized');
  }
};

export default handleAuth({
  callback: handleCallback({ afterCallback })
});
© www.soinside.com 2019 - 2024. All rights reserved.