Just to see if I understood the scenarios correctly, when you are using the isAuthenticated condition (even if it does not behave correctly, does it successfully log in the user after they have authenticated through the embedded component or not?
Yes, the user is successfully authenticated, but there is no redirect to the page from which they tried to log in - the user stays on the callback page with code and state in the URL. If I manually navigate to the original page, everything works well. At the same moment, on the dummy test page based on the auth0-react-samples
, it works as expected - the user is redirected to the page from appState.returnTo
.
Regarding the code snippet you provided in a previous message:
I need to rewrite it, because auth0.isAuthenticated().then(...
is not possible - isAuthenticated
is a boolean.
I assume it should be something like this:
const { getAccessTokenSilently, handleRedirectCallback, isAuthenticated, loginWithRedirect } =
useAuth0();
try {
if (!isAuthenticated) {
const query = window.location.search;
const shouldParseResult = query.includes("code=") && query.includes("state=");
if (shouldParseResult) {
console.log("> Parsing redirect");
try {
(async () => {
const result = await handleRedirectCallback();
console.log("result: ", result);
console.log("Logged in!");
})();
} catch (err) {
console.log("Error parsing redirect:", err);
}
window.history.replaceState({}, document.title, "/");
} else {
loginWithRedirect({
appState: {
redirect_uri: window.location.origin,
returnTo: window.location.href,
},
});
}
} else {
console.log("Not authenticated: ");
(async () => {
await getAccessTokenSilently().then((token) => {
console.log("token: ", token);
});
})();
}
} catch (err) {
console.log("Log in failed: ", err);
}
Could you please tell me exactly where I should place this code? I have tried different scenarios and get various errors, such as Error: You forgot to wrap your component in <Auth0Provider>
. If I wrap it with Auth0Provider
, I get nothing in the console log or encounter other strange errors.
Maybe this information will help:
I have a component called AuthWrapper
where I use Auth0Provider
and some other code for callback handling (I use this component for the /callback
path and also for paths that require authentication):
export const AuthWrapper = ({ children }: PropsWithChildren) => {
const navigate = useNavigate();
const [authState, setAuthState] = useState({
audience: "",
clientId: "",
domain: "",
});
const [urlSearchParams] = useSearchParams();
const { config } = useViewerState();
const gatherAuthState = useCallback(() => {
const authSessionKey = Object.keys(sessionStorage).find((key) =>
key.startsWith("a0.spajs.txs"),
);
const authSession = authSessionKey ? sessionStorage.getItem(authSessionKey) : null;
if (authSession && !authState.audience && !authState.clientId && !authState.domain) {
try {
const {
appState: {
config: { authentication },
},
audience,
} = JSON.parse(authSession) as Auth0State;
setAuthState({
audience,
clientId: authentication?.clientId ?? "",
domain: authentication?.domain ?? "",
});
} catch (error) {
console.error("Failed to parse auth session:", error);
}
}
}, [authState]);
useEffect(() => {
if (urlSearchParams.get("code") && urlSearchParams.get("state")) {
gatherAuthState();
}
}, [gatherAuthState, urlSearchParams]);
const isAuthConfigured = useMemo(
() =>
(config.authentication?.audience &&
config.authentication?.domain &&
config.authentication?.clientId) ??
(authState.audience && authState.clientId && authState.domain),
[
authState.audience,
authState.clientId,
authState.domain,
config.authentication?.audience,
config.authentication?.clientId,
config.authentication?.domain,
],
);
if (isAuthConfigured ?? config?.isLoginRequired) {
return (
<Auth0Provider
authorizationParams={{
audience: config.authentication?.audience ?? authState.audience,
redirect_uri: `${window.location.origin}/callback`,
}}
cacheLocation="localstorage"
clientId={config.authentication?.clientId ?? authState.clientId}
domain={config.authentication?.domain ?? authState.domain}
onRedirectCallback={(appState) => {
navigate(`/${appState?.returnTo ?? "/"}`, {
replace: true,
state: { skipWelcomePage: true },
});
}}
>
<SilentAuthenticationHandler />
{children}
</Auth0Provider>
);
}
return children;
};