页面刷新时未定义@ auth0 / auth0-spa-js isAuthenticated

时间:2020-01-26 17:25:30

标签: reactjs next.js auth0 server-side-rendering

我正在对我的应用进行身份验证,并且设法将登录信息添加到我的页面中。用户可以登录并存储他们的会话,但是,一旦我刷新页面,他们的会话就会消失。 ReactJs + NextJS

我知道有 getTokenSilently ,但是当我调用它时它将返回它!

error: "login_required"
error_description: "Login required"
state: "N3B+aWt4T1dBeGlibWsua2ZkdX5LTzR6T19ndTdXfkJ2Tm5kUzJIY3lXTQ=="

我在这里做错了什么?

  • 我的个人资料页面!
  useEffect(() => {
    if (typeof window !== `undefined`) {
      if (!loading && !isAuthenticated) {
        loginWithRedirect({})
      }
    }
  });
  • 如果用户已登录,则显示图标的首页!
          <Button
            className="account-button"
            variant="textButton"
            icon={<i className="flaticon-user" />}
            aria-label="login"
            title={loading ? 'loading' : isAuthenticated ? 'Hi' : 'login'}
          />
  • 身份验证服务
// src/react-auth0-spa.js
import React, { useState, useEffect, useContext } from "react";
import createAuth0Client from "@auth0/auth0-spa-js";

const DEFAULT_REDIRECT_CALLBACK = () =>
  window.history.replaceState({}, document.title, window.location.pathname);

export const Auth0Context = React.createContext();
export const useAuth0 = () => useContext(Auth0Context);
export const Auth0Provider = ({
  children,
  onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
  ...initOptions
}) => {
  const [isAuthenticated, setIsAuthenticated] = useState();
  const [user, setUser] = useState();
  const [auth0Client, setAuth0] = useState();
  const [loading, setLoading] = useState(true);
  const [popupOpen, setPopupOpen] = useState(false);

  useEffect(() => {
    const initAuth0 = async () => {
      const auth0FromHook = await createAuth0Client(initOptions);
      setAuth0(auth0FromHook);

      if (window.location.search.includes("code=") &&
          window.location.search.includes("state=")) {
        const { appState } = await auth0FromHook.handleRedirectCallback();
        onRedirectCallback(appState);
      }

      const isAuthenticated = await auth0FromHook.isAuthenticated();

      setIsAuthenticated(isAuthenticated);

      if (isAuthenticated) {
        const user = await auth0FromHook.getUser();
        setUser(user);
      }

      setLoading(false);
    };
    initAuth0();
    // eslint-disable-next-line
  }, []);

  const loginWithPopup = async (params = {}) => {
    setPopupOpen(true);
    try {
      await auth0Client.loginWithPopup(params);
    } catch (error) {
      console.error(error);
    } finally {
      setPopupOpen(false);
    }
    const user = await auth0Client.getUser();
    setUser(user);
    setIsAuthenticated(true);
  };

  const handleRedirectCallback = async () => {
    setLoading(true);
    await auth0Client.handleRedirectCallback();
    const user = await auth0Client.getUser();
    setLoading(false);
    setIsAuthenticated(true);
    setUser(user);
  };
  return (
    <Auth0Context.Provider
      value={{
        isAuthenticated,
        user,
        loading,
        popupOpen,
        loginWithPopup,
        handleRedirectCallback,
        getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
        loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
        getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
        getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
        logout: (...p) => auth0Client.logout(...p)
      }}
    >
      {children}
    </Auth0Context.Provider>
  );
};

1 个答案:

答案 0 :(得分:5)

问题出在使用《勇敢的浏览器》 !!!!!!此处有详细说明:

对。因此,无提示身份验证问题(“需要登录”错误)是您的浏览器未发送或无法发送“ auth0” cookie时得到的。一旦用户与Auth0进行会话(即用户已通过交互式流程登录),这就是Auth0在浏览器客户端上留下的cookie。您应该能够通过查看网络日志或分析HAR输出来确认这一点。有效的方案将附加cookie,而失败的方案则不会。如果是这样,这既不是示例问题,也不是SDK问题,因为它们不涉及该Cookie的设置;它是由授权服务器发出的。

如果浏览器无法发送此cookie,则最有可能是由于某些软件或浏览器扩展程序或阻止第三方跟踪cookie的原因。 Safari默认情况下会借助其内置的Intelligent Tracking Prevention(ITP2)1软件来执行此操作。这可以解释为什么静默身份验证可以在Chrome的隐身模式下工作,而不能在普通模式下工作。如果您正在运行某些扩展程序,则可能需要禁用其中一些扩展程序,以缩小阻止发送Cookie的范围。

我无法轻易解释的是它在Safari的“私有”模式下如何工作,因为我认为ITP2会阻止此类cookie。让我对此澄清一下。

https://community.auth0.com/t/failed-silent-auth-login-required/33165/24