我正在使用Auth0作为使用React的SPA的身份验证提供程序。我从他们的博客中关注了Auth0 react tutorial和this more detailed tutorial。
我目前仅使用电子邮件/密码身份验证。并且身份验证可以按预期的方式进行登录/注销,检索用户信息等。
但是,当我刷新页面时,isAuthenticated
中的useAuth0
值始终返回false。即使isLoading
解析为true后,因此我也必须再次登录。
奇怪的是,这种现象在Chrome或Firefox上不会发生。在Brave和Safari上失败。
我在Auth0(另一个有类似问题的人)的论坛帖子中注意到,Auth0Provider
应该使用authorize
进行prompte=none
呼叫,确实如此。页面加载后不久,它也会成功返回202
(但不会将isAuthenticated
更改为true
)。该调用还会设置一个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
这是我检查身份验证状态的路由。按照Auth0教程中的建议,该组件包装在Auth0ProviderWithHistory
代码中。
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
应该自动处理静默身份验证,不是吗?
auth0-react
npm软件包中使用的选项并不多,所以我不确定下一步该怎么做。唯一可用的功能是:
getAccessTokenSilently: ƒ (opts)
getAccessTokenWithPopup: ƒ (opts)
getIdTokenClaims: ƒ (opts)
isAuthenticated: false
isLoading: true
loginWithPopup: ƒ (opts)
loginWithRedirect: ƒ (opts)
如果这不可能,看来我可能必须迁移到@auth0/auth0-spa-js
SDK。
答案 0 :(得分:10)
问题是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