使用Auth0实现Gatsby受保护路由时出现重定向循环如何解决
问题根因
你的重定向循环来自于Auth0完成登录回调到/user路径时,SDK还未完成授权码换token的流程,isAuthenticated状态仍为false,此时跳转到受保护的/user/protectedpage会被withAuthenticationRequired再次判定为未登录,触发新一轮重定向,形成循环。你之前把回调地址改成根路径就正常,是因为根路径为公开页面,有足够的加载时间等待Auth0完成认证状态更新,再跳转受保护页面就不会触发二次重定向。
修复步骤
给
/user回调页面添加公开访问逻辑
确保src/pages/user/index.js没有被withAuthenticationRequired包裹,是完全公开的页面,这个页面的作用只是接收Auth0的回调请求,不需要额外业务逻辑,可仅显示加载提示:
// src/pages/user/index.js import React from 'react'; import { useAuth0 } from '@auth0/auth0-react'; const UserCallbackPage = () => { const { isLoading } = useAuth0(); return <div>{isLoading ? "登录处理中..." : null}</div>; }; export default UserCallbackPage;
调整Auth0Provider配置,等待认证状态加载完成再渲染应用
修改gatsby-browser.js,给根组件包裹一层Auth0加载状态判断,避免还没拿到认证状态就渲染受保护页面触发重定向:
// gatsby-browser.js import React from 'react'; import { Auth0Provider, useAuth0 } from '@auth0/auth0-react'; import { navigate } from 'gatsby'; const onRedirectCallback = (appState) => { navigate(appState?.returnTo || '/', { replace: true }); }; // 新增加载状态处理组件 const Auth0Loader = ({ children }) => { const { isLoading } = useAuth0(); if (isLoading) { return <div>加载中...</div>; } return children; }; export const wrapRootElement = ({ element }) => { return ( <Auth0Provider domain={process.env.AUTH0_DOMAIN} clientId={process.env.AUTH0_CLIENTID} redirectUri={window.location.origin + '/user'} onRedirectCallback={onRedirectCallback} // 新增以下两个参数,避免缓存导致的状态异常 useRefreshTokens={true} cacheLocation="localstorage" > <Auth0Loader>{element}</Auth0Loader> </Auth0Provider> ); };
确认Auth0后台配置完整
除了已配置的Allowed Callback URLs,还要在Auth0管理后台的应用配置里补充以下地址,配置后保存变更:
- Allowed Web Origins:
http://localhost:8000 - Allowed Logout URLs:
http://localhost:8000
按以上步骤修改后,登录回调到/user时会等待Auth0完成认证流程,isAuthenticated变为true之后再跳转回之前访问的受保护页面,不会再触发重定向循环。
内容的提问来源于stack exchange,提问作者Joseph K.
相关产品推荐
相关产品推荐

