在受 auth0 保护的 React 应用程序中使用 getAccessTokenSilently 时,为什么会收到“错误:需要外部交互”?

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

我的 auth0 静默令牌有问题。我正在使用 auth0 操作来执行 postRegister。问题是,当我想使用任何需要身份验证的 API 请求时。它给我错误:需要外部交互。我需要注销并重新登录才能修复它

您好!我的用户注册表有问题,我似乎找不到正确的解决方法,我正在使用一个操作:

import { Redirect } from 'react-router-dom';

exports.onExecutePostLogin = async (event, api) => {

  if(event.stats.logins_count <= 1){
      api.redirect.sendUserTo("http://localhost:5173/Informacion-Adicional")
  }else{
    api.redirect.sendUserTo
  }
};

exports.onContinuePostLogin = async (event, api) => {
};

我的州代码。 我只是传递了状态的一部分。这还不是全部

 const searchParams = new URLSearchParams(document.location.search)
  const state = searchParams.get('state')
  const [ continueUrl ] = useState(`https://dev-elbuensabor.us.auth0.com/continue?state=${state}`)

window.location.href = continueUrl;

//I have a fetch for the post data and it ends with a 

.finally(()=>{
       window.location.href = continueUrl;       
      });

问题是我的用户已经注册过一次。在您第一次登录(注册后默认登录)时,您无法以经过身份验证的用户身份执行任何操作。为了执行这些操作,我必须注销并再次登录。

当使用 useAuth0 isAuthenticated 时,我似乎确实经过了身份验证。问题是当我想执行其中一项获取来检索信息时

export default function ListaAlumnos() {
  const { getAccessTokenSilently } = useAuth0();
  
  const [alumnos, setAlumnos] = useState([]); 

  useEffect(() => {
    const fetchAlumnos = async () => {
      try {
        const token = await getAccessTokenSilently({
          audience: "localhost:8080/seguridad",
        });
        console.log("token " + token);

        const response = await fetch("http://localhost:8080/alumno", {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        const data = await response.json();
        setAlumnos(data); 
      } catch (error) {
        alert("error");
      }
    };

    fetchAlumnos();
  }, [getAccessTokenSilently]);

  return (
    <div>
      <h1>Aquí estará la lista de alumnos</h1>
      {alumnos.map((alumno) => (
        <div key={alumno.id}>{alumno.nombre}</div>
      ))}
    </div>
  );
}

这是我的功能,当我第一次登录进入这里时,我收到错误警报

问题是 getAccessTokenSilently。在我的控制台中显示:错误:需要外部交互。 任何帮助表示赞赏!

reactjs auth0
1个回答
0
投票

尽管我讨厌它,但答案是忽略它。您收到的此错误是通过静默身份验证过程发生的。在您的情况下,该“过程”是在调用

getAccessTokenSilently
时。

发生的情况是您的缓存中有一个无效的令牌。当

getAccessTokenSilenty
运行时,它会尝试使用当前令牌进行身份验证。如果该令牌已过期或无效,则会引发异常,最终仅意味着用户需要登录。

答案是仅当用户

实际上
经过身份验证时才运行getAccessTokenSilently。 Auth0 有一个名为
isAuthenticated$
的可用可观察对象,它可以为您处理其他一些逻辑。然而,
isAuthenticated$
只检查令牌是否存在,并不关心它的有效性。

就我而言,我使用

isAuthenticated$
并在运行
getAccessTokenSilently
之前检查令牌过期时间。

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