reactjs 无法在next.js中连接Auth0?

iecba09b  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(130)

我是Auth0的新手,正在尝试在next.js中设置一个登录小部件,它为登录用户提供access_tokenid_token。我有点卡住了,再也看不到登录小部件了。
到目前为止我所实施的
单位:_app.tsx

import { UserProvider, useUser } from '@auth0/nextjs-auth0/client';
import type { AppProps } from 'next/app';
import { Auth0Provider } from "@auth0/auth0-react";

function MyApp({ Component, pageProps }: AppProps) {

  return (
    <UserProvider>
      <Auth0Provider
        domain='mydomain.eu.auth0.com'
        clientId='my-client-secret'
      >
        <Component {...pageProps} />
      </Auth0Provider>
    </UserProvider>
  );
}

export default MyApp;

单位:index.tsx

import { useUser } from '@auth0/nextjs-auth0/client';
import { useRouter } from 'next/router';

export default function Home() {
  const { user, error, isLoading } = useUser();
  const router = useRouter();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  const handleLogout = async () => {
    try {
      await fetch('/api/auth/logout');
      router.push('/');
    } catch (err) {
      console.error('Failed to log out', err);
    }
  };

  if (user) {
    console.log('idToken:', user.idToken);
    console.log('accessToken:', user.accessToken);

    return (
      <div>
        <p>Welcome, {user.name}</p>
        <button onClick={handleLogout}>Logout</button>
      </div>
    );
  } else {
    return <a href="/api/auth/login">Login</a>;
  }
}

每当我在浏览器上打开应用程序时,我都会得到404的GET http://localhost:3000/api/auth/me 404(Not Found)
我做错了什么?我在next.js中找不到Auth0的官方文档,通过该文档我可以获得access_tokenid_token。但是,他们确实有reactjs的东西,但不幸的是,我使用的是next.js

ki1q1bka

ki1q1bka1#

首先,对于Auth 0配置,在“设置”页面的“应用程序URI”部分为应用程序配置以下URL:

Allowed Callback URLs: http://localhost:3000/api/auth/callback
Allowed Logout URLs: http://localhost:3000/

使用以下值创建.env文件:

# A long, secret value used to encrypt the session cookie
AUTH0_SECRET='LONG_RANDOM_VALUE'
# The base url of your application
AUTH0_BASE_URL='http://localhost:3000'
# The url of your Auth0 tenant domain
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
# Your Auth0 application's Client ID
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
# Your Auth0 application's Client Secret
AUTH0_CLIENT_SECRET='YOUR_AUTH0_CLIENT_SECRET'

如果你使用Next.js < 13和/pages文件夹:

Create an auth directory under the /pages/api/ directory.
Create a [auth0].js file under the newly created auth directory.

动态API路由文件的路径是/pages/api/auth/[auth 0]. js。添加到该文件:

import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();

在nextjs-auth 0的文档中:执行handleAuth()会在底层创建以下路由处理程序,它们执行身份验证流程的不同部分:

/api/auth/login: Your Next.js application redirects users to your identity provider for them to log in (you can optionally pass a returnTo parameter to return to a custom relative URL after login, for example /api/auth/login?returnTo=/profile).
/api/auth/callback: Your identity provider redirects users to this route after they successfully log in.
/api/auth/logout: Your Next.js application logs out the user.
/api/auth/me: You can fetch user profile information in JSON format.

使用UserProvider组件 Package pages/_app.js组件:

// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

消费身份验证:

// pages/index.js
import { useUser } from '@auth0/nextjs-auth0/client';

export default function Index() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  if (user) {
    return (
      <div>
        Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
      </div>
    );
  }

  return <a href="/api/auth/login">Login</a>;
}

如果你使用的是Next.js >= 13与App Router:

Create an api directory under the /app/ directory.
Create an auth directory under the newly created /app/api/ directory.
Create a [auth0] directory under the newly created auth directory.
Create a route.js file under the newly created [auth0] directory.

动态API路由文件的路径为/app/api/auth/[auth 0]/route. js。
添加到该文件:

import { handleAuth } from '@auth0/nextjs-auth0';

export const GET = handleAuth();

使用UserProvider组件 Package app/layout.js组件:

// app/layout.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export default function App({ children }) {
  return (
    <UserProvider>
      <body>{children}</body>
    </UserProvider>
  );
}

消费身份验证:

// pages/index.js
'use client';
import { useUser } from '@auth0/nextjs-auth0/client';

export default function Index() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  if (user) {
    return (
      <div>
        Welcome {user.name}! <a href="/api/auth/logout">Logout</a>
      </div>
    );
  }

  return <a href="/api/auth/login">Login</a>;
}

相关问题