I am implementing a React sign on with local storage. I chose local storage because I don’t want my users to need to reauth every time they refresh the page.
The problem I am having is that I seem unable to pull the token from local storage with getAccessTokenSilently()
. I do however have access to local storage with thee typical JavaScript methods.
My implementation is straight forward:
<React.StrictMode>
<Auth0Provider
domain={domain}
clientId={clientId}
authorizationParams={{
redirect_uri: window.location.origin,
audience: audience,
scope: "openid profile email offline_access",
}}
useRefreshTokens={true}
cacheLocation="localstorage"
>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
</Auth0Provider>
</React.StrictMode>
and
useEffect(() => {
const checkUsername = async () => {
if (isAuthenticated) {
try {
const token = await getAccessTokenSilently({
authorizationParams: {
audience: AUTH0_AUDIENCE,
scope: "openid profile email offline_access",
},
});
if (!token) {
throw new Error("Access token is undefined");
}
console.log("Token available:", !!token);
const response = await fetch("/api/v1/users/me", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setHasUsername(!!data.username);
} catch (error) {
console.error("Failed to check username:", error);
setHasUsername(false);
}
}
setCheckingUsername(false);
};
checkUsername();
}, [isAuthenticated, getAccessTokenSilently]);
As I research the issue more it seems like the problem is that getAccessTokenSilently
uses some type of Iframe which is blocked from accessing local storage by the browser.
Surely their must be a way to use Auth0 with common browsers and not require a user to reauth on every page refresh.