Search code examples
javascriptreactjsjwtfetch

Error on fetch get request with React and Authorization header


I've been looking for a solution for days but haven't found anything yet.

I have a jwt token from localstorage and I need to verify with an api call. The problem is that the response from my api is always "Invalid token". This ONLY happens when the fetch is executed by my react app because if I copy-paste the request without changing anything in the console, the call is validated without problems.

MY CODE THAT DOESNT WORK

const token = localStorage.getItem('token'); fetch("http://localhost/api/checktoken.php?username=davide", { method: 'GET', headers:{ 'Content-Type': 'application/json', 'Authorization': "Bearer " + token, }, })

MY CODE THAT WORK

fetch(`http://localhost/api/checktoken.php?username=davide`, {
    method: 'GET',
    
    'Content-Type': 'application/json',
    headers: {
      Authorization: `Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJvbmNvbnN1bHRpbmciLCJhdWQiOiJjbGllbnRzIiwiaWF0IjoxNzAxNTI5NjgyLCJuYmYiOjE3MDE1Mjk2OTIsImRhdGEiOnsidXNlcm5hbWUiOiJkYXZpZGUuZ2FnbGlvbmUiLCJsYW5ndWFnZSI6IkVuZyIsImVudmlyb25tZW50cyI6W3sibmFtZSI6ImVudjEifSx7Im5hbWUiOiJlbnYyIn1dfX0.iC2NntlW6rFx2s6pacSFw6Y_5ib3Bh8jhFl2-MMTX-Q`,
    },
  })

I verified that:

  • the jwt passed by the frontend is correct
  • the jwt is actually taken from localstorage before the request.
  • the request has the correct jwt

The strange thing is that if I put the jwt directly in the react code, the request is validated, but if I do a concatenation it doesn't work


Solution

  • I discovered by debugging the backend, not done by me, that the server that creates the token used a "nbf" parameter which indicates the start of validity of the token and this parameter was set to actual time + 100, so the token is valid after 100 seconds and not immediately. By removing +100, the token is validated correctly.