correct-apricot
correct-apricotโ€ข2y ago

Auth0 authProvider and dataProvider async problem

I have an Auth0 login on my Refine frontend. Once I'm logged in I pass my token to the backend via the Authorization header as a bearer token. The issue is that Refine does not wait for the checkAuth to return true before making requests to the dataProvider which requires auth. Since Auth0 is async, the first couple of queries on page reload will fail. How do I prevent Refine from starting to query resources before the user is logged in? I can't wrap <Refine> because I need to have the login page.
5 Replies
Omer
Omerโ€ข2y ago
Hey @geoffatsource ๐Ÿ‘‹, Could you share your AuthProvider?
correct-apricot
correct-apricotโ€ข2y ago
Actually I got it working by modifying my App.tsx like so
useEffect(() => {
getIdTokenClaims().then((token) => {
if (isAuthenticated && token) {
client.setHeader("Authorization", `Bearer ${token.__raw}`);
}
if (!authIsLoading) {
setAuthSynced(true);
}
});
}, [authIsLoading, isAuthenticated, getIdTokenClaims]);

if (authIsLoading || !authSynced) {
return <span>Loading...</span>;
}
useEffect(() => {
getIdTokenClaims().then((token) => {
if (isAuthenticated && token) {
client.setHeader("Authorization", `Bearer ${token.__raw}`);
}
if (!authIsLoading) {
setAuthSynced(true);
}
});
}, [authIsLoading, isAuthenticated, getIdTokenClaims]);

if (authIsLoading || !authSynced) {
return <span>Loading...</span>;
}
authIsLoading comes from const { isLoading: authIsLoading } = useAuth0();
Omer
Omerโ€ข2y ago
Does everything work as expected in our example? ๐Ÿ‘€ https://refine.dev/docs/examples/auth-provider/auth0/
Auth0 | refine
Auth0 is a modular, API-first authentication and authorization service that you may use to add authentication and authorization to your apps. In this example, you'll see how to use Auth0 Login with refine.
correct-apricot
correct-apricotโ€ข2y ago
Essentially, yes, because your backend doesn't require any auth integration. For my purposes, I need login to complete isLoading in order to place the raw token into the Authorization header in my backend client. This only is a problem when the user is already logged in and has a valid session, in which case Auth0 will log in silently. My code above ensures that the dataProvider is either properly authorized or the user doesn't have a valid login session before Refine starts.
Omer
Omerโ€ข2y ago
Ohh I see! I've fixed this issue. You can check out our Auth0 example now. Thank you ๐Ÿ’ฏ https://github.com/pankod/refine/blob/next/examples/authProvider/auth0/src/App.tsx#L36
GitHub
refine/App.tsx at next ยท pankod/refine
Build your React-based CRUD applications, without constraints. - refine/App.tsx at next ยท pankod/refine