title: auth0 jwt authentication Error parsing token: Token used before issued
body: <p>I have successfully setup authentication with Auth0 however when Auth0 redirects back to my callback, I then can't access ajax endpoints. </p>
  
  <p>However, if I refresh the page (without going through authentication again), I now can. I can see in localStorage that the <code>access_token</code> has been set. So it seems odd that when I refresh the token is set but the first time its not.</p>
  
  <p>I suspect I am loading components before localStorage is setup, and that means that the request to the api fails. However I'm not sure of the fix.</p>
  
  <p>I get the error <code>Error parsing token: Token used before issued</code> and a 401 on the request to the api</p>
  
  <p>My code is below:</p>
  
  <p>Im using libraries</p>
  
  <pre><code>"github.com/auth0/go-jwt-middleware"
  "github.com/dgrijalva/jwt-go"
  </code></pre>
  
  <p>I initialise the verification of the token here:</p>
  
  <pre><code>func (h *Page) Init() error {
      h.JWTMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
          ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
              aud := os.Getenv("AUTH0_API_AUDIENCE")
              checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, false)
              if !checkAudience {
                  return token, errors.New("Invalid audience.")
              }
              // verify iss claim
              iss := os.Getenv("AUTH0_DOMAIN")
              fmt.Println("iss == ", iss)
              checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false)
              if !checkIss {
                  return token, errors.New("Invalid issuer.")
              }
  
              cert, err := getPemCert(token)
              if err != nil {
                  fmt.Println("could not get cert: %+v", err)
                  return cert, err
              }
  
              result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
              return result, nil
          },
          SigningMethod: jwt.SigningMethodRS256,
      })
  
      return nil
  }
  </code></pre>
  
  <p>I configure the pem and my middleware here</p>
  
  <pre><code>func (h *Page) authMiddleware() gin.HandlerFunc {
      return func(c *gin.Context) {
          // Get the client secret key
          err := h.JWTMiddleware.CheckJWT(c.Writer, c.Request)
          if err != nil {
              // Token not found
              fmt.Println("error checking jwt ", err)           &lt;&lt;&lt;---- FAILS HERE!
              c.Abort()
              c.Writer.WriteHeader(http.StatusUnauthorized)
              c.Writer.Write([]byte("Unauthorized"))
              return
          }
      }
  }
  
  func getPemCert(token *jwt.Token) (string, error) {
      cert := ""
      resp, err := http.Get(os.Getenv("AUTH0_DOMAIN") + ".well-known/jwks.json")
      if err != nil {
          return cert, err
      }
      defer resp.Body.Close()
  
      var jwks = Jwks{}
      err = json.NewDecoder(resp.Body).Decode(&amp;jwks)
  
      if err != nil {
          return cert, err
      }
  
      x5c := jwks.Keys[0].X5c
      for k, v := range x5c {
          if token.Header["kid"] == jwks.Keys[k].Kid {
              cert = "-----BEGIN CERTIFICATE-----\n" + v + "\n-----END CERTIFICATE-----"
          }
      }
      if cert == "" {
          return cert, errors.New("unable to find appropriate key")
      }
  
      return cert, nil
  }
  </code></pre>
  
  <p>and my react frontend is here</p>
  
  <pre><code>
  const AUTH0_CLIENT_ID = "xxx7vOQeStuKmaNfwxoWX"//'{{ $variables := index .Globals "jokish.so"}}{{index $variables "auth0-key"}}';
  const AUTH0_DOMAIN = "xxx.eu.auth0.com"//'{{ $variables := index .Globals "jokish.so"}}{{index $variables "domain"}}';
  const AUTH0_CALLBACK_URL = "http://localhost:9000/jokes/callback"//'{{ $variables := index .Globals "jokish.so"}}{{index $variables "callback"}}';
  const AUTH0_API_AUDIENCE = "https://xxx.eu.auth0.com/api/v2/"//'{{ $variables := index .Globals "jokish.so"}}{{index $variables "audience"}}';
  
  class App extends React.Component {
      parseHash() {
          this.auth0 = new auth0.WebAuth({
              domain: AUTH0_DOMAIN,
              clientID: AUTH0_CLIENT_ID
          });
          this.auth0.parseHash(window.location.hash, (err, authResult) =&gt; {
              if (err) {
                  return console.log(err);
              }
              if (
                  authResult !== null &amp;&amp;
                  authResult.accessToken !== null &amp;&amp;
                  authResult.idToken !== null
              ) {
                  localStorage.setItem("access_token", authResult.accessToken);
                  localStorage.setItem("id_token", authResult.idToken);
                  localStorage.setItem(
                      "profile",
                      JSON.stringify(authResult.idTokenPayload)
                  );
                  window.location = window.location.href.substr(
                      0,
                      window.location.href.indexOf("#")
                  );
              }
          });
      }
  
      setup() {
          $.ajaxSetup({
              beforeSend: (r) =&gt; {
                  console.log("setting ajax up with token ", localStorage.getItem("access_token"))
                  if (localStorage.getItem("access_token")) {
                      r.setRequestHeader(
                          "Authorization",
                          "Bearer " + localStorage.getItem("access_token")
                      );
                  }
              }
          });
      }
  
      setState() {
          let idToken = localStorage.getItem("id_token");
          if (idToken) {
              this.loggedIn = true;
          } else {
              this.loggedIn = false;
          }
      }
  
      componentWillMount() {
          this.setup();
          this.parseHash();
          this.setState();
      }
  
      render() {
          if (this.loggedIn) {
              return &lt;LoggedIn /&gt;;
          }
          return &lt;Home /&gt;;
      }
  }
  
  class Home extends React.Component {
      constructor(props) {
          super(props);
          this.authenticate = this.authenticate.bind(this);
      }
      authenticate() {
          this.WebAuth = new auth0.WebAuth({
              domain: AUTH0_DOMAIN,
              clientID: AUTH0_CLIENT_ID,
              scope: "openid profile",
              audience: AUTH0_API_AUDIENCE,
              responseType: "token id_token",
              redirectUri: AUTH0_CALLBACK_URL
          });
          this.WebAuth.authorize();
      }
  
      render() {
          return (
              &lt;div className="container"&gt;
                  &lt;div className="row"&gt;
                      &lt;div className="col-xs-8 col-xs-offset-2 jumbotron text-center"&gt;
                          &lt;h1&gt;Jokeish&lt;/h1&gt;
                          &lt;p&gt;A load of Dad jokes XD&lt;/p&gt;
                          &lt;p&gt;Sign in to get access &lt;/p&gt;
                          &lt;a
                              onClick={this.authenticate}
                              className="btn btn-primary btn-lg btn-login btn-block"
                          &gt;
                              Sign In
                          &lt;/a&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          );
      }
  }
  
  class LoggedIn extends React.Component {
      constructor(props) {
          super(props);
          this.state = {
              jokes: []
          };
  
          this.serverRequest = this.serverRequest.bind(this);
          this.logout = this.logout.bind(this);
      }
  
      logout() {
          localStorage.removeItem("id_token");
          localStorage.removeItem("access_token");
          localStorage.removeItem("profile");
          location.reload();
      }
  
      serverRequest() {
          $.get("http://localhost:9000/jokes/api/jokes", res =&gt; {
              this.setState({
                  jokes: res
              });
          });
      }
  
      componentDidMount() {
          this.serverRequest();
      }
  
      render() {
          return (
              &lt;div className="container"&gt;
                  &lt;br /&gt;
                  &lt;span className="pull-right"&gt;
            &lt;a onClick={this.logout}&gt;Log out&lt;/a&gt;
          &lt;/span&gt;
                  &lt;h2&gt;Jokeish&lt;/h2&gt;
                  &lt;p&gt;Let's feed you with some funny Jokes!!!&lt;/p&gt;
                  &lt;div className="row"&gt;
                      &lt;div className="container"&gt;
                          {this.state.jokes.map(function(joke, i) {
                              return &lt;Joke key={i} joke={joke} /&gt;;
                          })}
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          );
      }
  }
  
  class Joke extends React.Component {
      constructor(props) {
          super(props);
          this.state = {
              liked: "",
              jokes: []
          };
          this.like = this.like.bind(this);
          this.serverRequest = this.serverRequest.bind(this);
      }
  
      like() {
          let joke = this.props.joke;
          this.serverRequest(joke);
      }
      serverRequest(joke) {
          $.post(
              "http://localhost:9000/jokes/api/jokes/like/" + joke.id,
              { like: 1 },
              res =&gt; {
                  console.log("res... ", res);
                  this.setState({ liked: "Liked!", jokes: res });
                  this.props.jokes = res;
              }
          );
      }
  
      render() {
          return (
              &lt;div className="col-xs-4"&gt;
                  &lt;div className="panel panel-default"&gt;
                      &lt;div className="panel-heading"&gt;
                          #{this.props.joke.id}{" "}
                          &lt;span className="pull-right"&gt;{this.state.liked}&lt;/span&gt;
                      &lt;/div&gt;
                      &lt;div className="panel-body joke-hld"&gt;{this.props.joke.joke}&lt;/div&gt;
                      &lt;div className="panel-footer"&gt;
                          {this.props.joke.likes} Likes &amp;nbsp;
                          &lt;a onClick={this.like} className="btn btn-default"&gt;
                              &lt;span className="glyphicon glyphicon-thumbs-up" /&gt;
                          &lt;/a&gt;
                      &lt;/div&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          );
      }
  }
  ReactDOM.render(&lt;App /&gt;, document.getElementById("app"));
  
  </code></pre>