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
4
Answers
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.
Looks like you put the wrong username,
davide
instead ofdavide.gaglione
In the ‘network’ tab of Google Dev Tools, do you see the JWT token? Also, in the code that doesn’t work, username is equal to ‘davide,’ whereas in the code that works, it’s ‘davide.gaglione.’
Is the JWT token from LocalStorage a string?
Try comparing the working token with the one from LocalStorage.
Try using axios instead and make sure that the token is actually in the local storage then you make sure you properly passing the right headers , params in the axios fetch. Oh yeah put this all in a function or useEffect.