So I'm creating a simple React Redux app using superagent to get some elements from the database and do some operations on them. I used Symfony's Api platform as a backend and created a few of APIs. All my APIs are protected and need a bearer token to access them. I created an Authentication API using JWT.
Now I'm trying to get the data to show in my React app. I already created a functioning login form. I can use my username and password and get a token in return.
My problem though, is after I authenticate and the app redirects me to my homepage (which contains the list of elements from the db), I get an error in my console
("{code: 401, message: "JWT Token not found"}
code: 401
message: "JWT Token not found")
which means that I'm not using the bearer token in my request.
So how do I use the token inside my POST, GET and PUT requests so I can use them.
PS: My token is stored inside my localstorage under the name jwtToken here's my agent.js file:
import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';
const superagent = superagentPromise(_superagent,global.Promise);
const API_ROOT='http://localhost:8000/api';
const responseBody = response => response.body;
let token =window.localStorage.getItem('jwtToken');;
const tokenPlugin = secured => {
return (request) => {
if (token && secured){
request.set('Authorization',`Bearer ${token}`);
}
};
};
export const requests={
get: (url, secured = false)=>{
return superagent.get(`${API_ROOT}${url}`).use(tokenPlugin(secured)).then(responseBody);
},
post: (url, body = null, secured = true) => {
return superagent.post(`${API_ROOT}${url}`, body).use(tokenPlugin(secured)).then(responseBody);
},
setToken: (newJwtToken) => token = newJwtToken
};
Your get accepts url
and secured
params and maybe you are not sending the second param and it is defaulted to false and tokenPlugin is checking for token && secured
try get(url, true)
where you are using the get
.