Followed react tutorial, get "Invalid authorization code" when I first login

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:

image

image

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?

I should say that when I refresh the page, it works nicely. It’s only the first time you login that I get this error.

Hey there Jack!

Have you followed the steps described in the quickstart thoroughly? Just making sure before I report it to the quickstart author

I’ve just copied and pasted the code exactly to overwrite what I’ve done. I get this error every time on a first login. Subsequently, it’s fine.

1 Like

Just for more information, I setup a new tenant and it worked perfectly twice in a row (login, then logout). Third time I tried it failed with the same error.

{"error":"invalid_grant","error_description":"Invalid authorization code"}

From the logs

    {
  "date": "2020-03-03T11:12:40.032Z",
  "type": "feacft",
  "description": "Invalid authorization code",
  "connection_id": "",
  "client_id": "<MYCLIENTID>",
  "client_name": "Test",
  "ip": "<MYIP>",
  "user_agent": "Chrome 80.0.3987 / Mac OS X 10.15.2",
  "details": {
    "code": "*************2cH",
    "device_id": "v0:e5564320-5d3f-11ea-bdc0-8324d96507a0"
  },
  "hostname": "<MYDOMAIN>",
  "user_id": "",
  "user_name": "",
  "log_id": "90020200303111240356000988326657551290219170667496996898",
  "_id": "90020200303111240356000988326657551290219170667496996898",
  "isMobile": false
}

Gotchya let me bring it to attention of the quickstart author - @steve.hobbs!

1 Like

I’ve fixed this. I have Auth0Provider wrapping App twice. :see_no_evil:

2 Likes

Perfect! Glad to hear that!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.