Hi everyone
I’ve followed the tutorial here: Auth0 React SDK Quickstarts: Login
It doesn’t work the first time you login, and I get an “Invalid Authorization Code” error. The logs show the below:
I have put the code into a useAuth0 hook as per the below:
import React, { useState, useEffect, useContext } from "react";
import PropTypes from "prop-types";
import createAuth0Client from "@auth0/auth0-spa-js";
// Specify default callback as the existing link
const DEFAULT_REDIRECT_CALLBACK = () => {
window.history.replaceState({}, document.title, window.location.pathname);
};
export const Auth0Context = React.createContext();
export const useAuth0 = () => useContext(Auth0Context);
export const Auth0Provider = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
...initOptions
}) => {
const [isAuthenticated, setIsAuthenticated] = useState();
const [user, setUser] = useState();
const [auth0Client, setAuth0] = useState();
const [loading, setLoading] = useState(true);
const [popupOpen, setPopupOpen] = useState(false);
// Handle whether the user is authenticated, if so load their details
useEffect(() => {
const initAuth0 = async () => {
// Initiate auth0 and assign it to auth0Client state
const auth0FromHook = await createAuth0Client(initOptions);
setAuth0(auth0FromHook);
// If we can see a code + state in the url, perform the redirect callback
if (
window.location.search.includes("code=") &&
window.location.search.includes("state=")
) {
const { appState } = await auth0FromHook.handleRedirectCallback();
onRedirectCallback(appState);
}
// Set state based on whether authenticated
const isAuthenticatedNow = await auth0FromHook.isAuthenticated();
setIsAuthenticated(isAuthenticatedNow);
console.log(isAuthenticatedNow, isAuthenticated);
// If authenticated, get and set the user
if (isAuthenticated) {
const userDetails = await auth0FromHook.getUser();
setUser(userDetails);
}
setLoading(false);
};
initAuth0();
}, [isAuthenticated]);
const handleRedirectCallback = async () => {
setLoading(true);
// Callback and get user details
await auth0Client.handleRedirectCallback();
const userDetails = await auth0Client.getUser();
setLoading(false);
setIsAuthenticated(true);
setUser(userDetails);
};
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
logout: (...p) => auth0Client.logout(...p)
}}
>
{children}
</Auth0Context.Provider>
);
};
Auth0Provider.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired,
onRedirectCallback: PropTypes.func
};
Auth0Provider.defaultProps = {
onRedirectCallback: () =>
window.history.replaceState({}, document.title, window.location.pathname)
};
Any ideas what I can do to resolve this?