13

我使用 Auth0 作为我使用 React 的 SPA 的身份验证提供程序。我已经按照他们博客中的Auth0 react 教程这个更详细的教程进行了操作。

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

但是,当我刷新页面时,isAuthenticated总是useAuth0返回 false。即使isLoading解析为真,因此我必须再次登录。

奇怪的是,这种行为在 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 仪表板的应用程序的“快速启动”部分下载了反应示例,​​以查看该行为是否在此处复制。确实如此。

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

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

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

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

4

1 回答 1

22

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

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

要添加的两个新道具是: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

于 2020-08-27T16:22:30.247 回答