使用 Auth0 和 AuthenticationRequired 登录不会显示在 Gatsby 中

Login doesn't show up in Gatsby using Auth0, withAuthenticationRequired

我将 Gatsby 与 auth0 一起使用,当我用 withAuthenticationRequired 包装一个页面时,我得到一个空白页面,上面写着“正在重定向...”

import * as React from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';


const UserIndexPage = () => {
  return (
    <div>
      User index page
    </div>
  );
};

export default withAuthenticationRequired(UserIndexPage, {
  onRedirecting: () => <div>Redirecting...</div>
});

登录屏幕没有出现,页面卡在重定向消息中

如果我创建了一个没有 withAuthenticationRequired 的登录按钮,那么当我点击它时会出现登录屏幕

const LoginButton = () => {
  const { loginWithRedirect } = useAuth0();
  return <button onClick={() => loginWithRedirect()}>Log In</button>;
};

查看发布的新实现我认为 onRedirect 回调应该由 Gatsby 浏览器管理 (gatsby-browser.js):

import React from 'react';
import { Auth0Provider } from '@auth0/auth0-react';
import { navigate } from 'gatsby';

const onRedirectCallback = (appState) => {
  navigate(appState?.returnTo || '/', { replace: true });
};

export const wrapRootElement = ({ element }) => {
  return (
    <Auth0Provider
      domain="YOUR_AUTH0_DOMAIN"
      clientId="YOUR_AUTH0_CLIENT_ID"
      redirectUri={window.location.origin}
      onRedirectCallback={onRedirectCallback}
    >
      {element}
    </Auth0Provider>
  );
};

在您的 UI 视图中:

import * as React from 'react';
import { withAuthenticationRequired } from '@auth0/auth0-react';


const UserIndexPage = () => {
  return (
    <div>
      User index page
    </div>
  );
};

export default withAuthenticationRequired(UserIndexPage);

想法是将组件包装在 withAuthenticationRequired 处理程序中。

onRedirectCallback 将使用 Gatsby 的 navigate 函数 return 用户登录后到受保护的路由,并将替换 URL 以避免奇怪的行为时用户正试图向前和向后移动。