使用 next.js 中的自定义 Auth0Server 实例调用 withMiddlewareAuthRequired

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

在我的 next.js 项目中,我无法使用 auth0 库所需的默认环境变量名称,因此想要实例化我自己的 Auth0Server,为其提供自定义环境变量来设置所需的配置(auth0 密钥、客户端 ID、 ETC。)。此外,我使用

middelware.js
文件通过在其中导出
withMiddlewareAuthRequired
来指定受保护的路由。当使用默认命名约定(在开发环境中)时,我不需要实例化自己的 Auth0Server,并且可以使用默认导入,一切都按预期工作。

据我所知实施它(参见下面的 MWE),会导致错误

- error node_modules/oidc-token-hash/lib/shake256.js (3:0) @ <unknown>
- error Cannot read properties of undefined (reading 'substring')
null

我认为这是因为我从我的

middleware.js
文件间接导入了 auth0 库文件。我确信我错过了一些基本的东西,但是如何使用自定义 Auth0Server 实例实现同样的事情?

要重新创建一个最小的工作(或不工作)示例,我只需调用

npx create-next-app
,选择所有默认值,安装
@auth0/nextjs-auth0
版本
3.1.0
,并添加/修改以下文件。

  • Next.js 版本 13.4.19
// file src/pages/_app.tsx

import '@/styles/globals.css'
import type { AppProps } from 'next/app'
import { UserProvider } from '@auth0/nextjs-auth0/client'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
        <Component {...pageProps} />
    </UserProvider>
  )
}
// file src/auth0.js
// DEFAULT (working)

// Nothing to be added.

// CUSTOM (not working)
import { initAuth0 } from "@auth0/nextjs-auth0";
const auth0 = initAuth0({
    baseURL: process.env.CUSTOM_AUTH0_BASE_URL,
    clientID: process.env.CUSTOM_AUTH0_CLIENT_ID,
    clientSecret: process.env.CUSTOM_AUTH0_CLIENT_SECRET,
    issuerBaseURL: process.env.CUSTOM_AUTH0_ISSUER_BASE_URL,
    secret: process.env.CUSTOM_AUTH0_SECRET
});

export {auth0};
// file src/pages/api/auth/[...auth0].js

// DEFAULT (working)
// import { handleAuth } from "@auth0/nextjs-auth0";
// export default handleAuth();

// CUSTOM (not working)
import { auth0 } from '@/auth0';
export default auth0.handleAuth();
// file src/middleware.js
// DEFAULT (working)
// import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
// export default withMiddlewareAuthRequired();
// export const config = {
//     matcher: [
//         '/((?!api|favicon.ico|logo-dark.jpg).*)'
//     ]
// };

// CUSTOM (not working)
import { auth0 } from '@/auth0';
export default auth0.withMiddlewareAuthRequired();
export const config = {
    matcher: [
        '/((?!api|favicon.ico|logo-dark.jpg).*)'
    ]
};
// file .env.local
// DEFAULT (working)
// AUTH0_BASE_URL="value"
// AUTH0_CLIENT_ID="value"
// AUTH0_CLIENT_SECRET="value"
// AUTH0_ISSUER_BASE_URL="value"
// AUTH0_SECRET="value"

// CUSTOM (not working)
CUSTOM_AUTH0_BASE_URL="value"
CUSTOM_AUTH0_CLIENT_ID="value"
CUSTOM_AUTH0_CLIENT_SECRET="value"
CUSTOM_AUTH0_ISSUER_BASE_URL="value"
CUSTOM_AUTH0_SECRET="value"
next.js auth0
1个回答
0
投票

我认为您需要使用中间件兼容(Edge 运行时兼容)初始化程序来初始化 SDK 实例。而不是:

import { initAuth0 } from "@auth0/nextjs-auth0"

用途:

import { initAuth0 } from "@auth0/nextjs-auth0/edge"
.

但是,我不确定这是否是您唯一需要的东西。我正在尝试实现同样的目标,但没有成功。你能让它发挥作用吗?

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