Auth0 不会在页面刷新时为电子邮件/密码持续登录

IT技术 javascript reactjs auth0 auth0-lock
2021-05-11 15:02:20

我使用 Auth0 作为使用 React 的 SPA 的身份验证提供程序。我遵循了他们博客中Auth0 react 教程这个更详细的教程

我目前只使用电子邮件/密码身份验证。并且身份验证按预期进行登录/注销,检索用户信息等。

但是,当我刷新页面时,isAuthenticated来自的值useAuth0总是返回 false。即使在isLoading解析为 true 之后,我也必须再次登录。

奇怪的是,这种行为不会在 Chrome 或 Firefox 上发生。它在 Brave 和 Safari 上失败。

我在 Auth0(另一个有类似问题的人)的论坛帖子中注意到,Auth0Provider应该authorize使用 拨打电话prompte=none,确实如此。它还202在页面加载后不久返回成功(但不会更改isAuthenticatedtrue)。此调用还设置了一个 cookie auth0.is.authenticated=true

authorize?client_id=VALUE&redirect_uri=VALUE&scope=openid%20profile%20email&response_type=code&response_mode=web_message&state=VALUE&nonce=VALUE&code_challenge=VALUE&code_challenge_method=S256&prompt=none&auth0Client=VALUE

这是我检查身份验证状态的路线。该组件Auth0ProviderWithHistory按照 Auth0 教程中的建议封装在代码中。

export default function Routes() {
  const { isLoading, isAuthenticated } = useAuth0()

  const getDashboard = () => {
    //determine which dashboard to return
  }

  if (isLoading) return <p>Loading...</p>

  if (isAuthenticated) {
    return (
      <Suspense fallback={<p>loading...</p>}>
        <Switch>
          <Route exact path="/">
            {getDashboard()}
          </Route>
          <Route path="/customer/:customerId">
            <Customer />
          </Route>
          <Route>
            <NotFound />
          </Route>
        </Switch>
      </Suspense>
    )
  }

  return <SignInAndRegister />
}

我注意到当我重新加载页面并调用loginWithRedirect函数时,我没有重定向到通用登录页面,而是有两个令牌调用(POST 和 OPTIONS)。POST 调用响应具有以下详细信息,我应该以某种方式捕获它并保存它们以重新使用它们来登录吗?

access_token: "VALUE"
expires_in: 86400
id_token: "VALUE"
scope: "openid profile email"
token_type: "Bearer"

作为一项实验,我在 Auth0 仪表板中应用程序的“快速入门”部分下载了react示例,​​以查看该行为是否在那里复制。确实如此。

我的印象是Auth0Provider应该自动处理静默身份验证,不是这样吗?

auth0-reactnpm 包一起使用的选项不多,所以我不确定接下来要尝试什么。唯一可用的功能是:

getAccessTokenSilently: ƒ (opts)
getAccessTokenWithPopup: ƒ (opts)
getIdTokenClaims: ƒ (opts)
isAuthenticated: false
isLoading: true
loginWithPopup: ƒ (opts)
loginWithRedirect: ƒ (opts)

如果这是不可能的,看起来我可能不得不迁移到@auth0/auth0-spa-jsSDK。

1个回答

问题是 Brave 和 Safari 都使用智能跟踪预防 (ITP),这阻止了静默身份验证的工作。

对我有用的解决方案是启用轮换刷新令牌(通过 Auth0 仪表板)并向 Auth0 提供程序提供额外的props。

要添加的两个新props是:useRefreshTokens={true}cacheLocation="localstorage"

<Auth0Provider
  domain={process.env.REACT_APP_AUTH0_DOMAIN}
  clientId={process.env.REACT_APP_AUTH0_CLIENT_ID}
  redirectUri={window.location.origin}
  onRedirectCallback={onRedirectCallback}
  useRefreshTokens={true}
  cacheLocation="localstorage"
>
  {children}
</Auth0Provider>

以下是了解有关轮换刷新令牌的更多信息的官方文档:https : //auth0.com/docs/tokens/refresh-tokens