1
Hello I would like to know how I could send a jwt in my header to consume in my API, a route get to catch users ( need auth )
my api to catch users:
app.route('/users') .all(app.auth.authenticate()) .get((req,res)=>{ usersController .getAll() .then(data => { res.json(data); }) .catch(error=>{ console.log(error); res.status(400); }); })
and my jwt auth ( . all(app.auth.authenticate()) ) :
authenticate: () => passport.authenticate('jwt', jwtConfig.session)
on my front end I don’t know how I’m going to make this request:
getDate = () => {
console.log(JSON.parse(sessionStorage.getItem('token')));
const data = {token: sessionStorage.getItem('token')};
const requestInfo = {
method:'GET',
body: JSON.stringify({data}),
headers: new Headers({
'Content-Type': 'application/json'
}),
};
console.log('chegouaq');
fetch('http://localhost:9000/users', requestInfo)
.then(response => {
console.log('chegouaq2');
if(response.ok){
return response.json();
}
throw new Error("Token Invalido..")
})
.then(data => {
console.log(JSON.stringify(data));
return;
})
.catch(e => {
this.setState({message: e.message})
console.error(e);
});
}
I know get doesn’t accept the body, but I have no idea how to send my jwt in the header.
///
My way of generating jwt when logging in:
app.route('/login')
.post(async (req,res)=>{
try {
const response = await usersControllers.signin(req.body);
const login = response.login;
console.log(login);
if(login.id && login.isValid){
const payload = {id: login.id};
res.json({
token: jwt.sign({data:payload}, app.config.jwt.secret,{expiresIn: '60'}),
response
});
}else{
console.log('entrou here');
res.sendStatus(HttpStatus.UNAUTHORIZED);
}
} catch (error) {
console.log('entrou here');
console.error(error.message);
res.sendStatus(HttpStatus.UNAUTHORIZED);
}
})
and my Strategy:
const strategy = new Strategy(options,(payload, done) => {
Users
.findOne({where: payload.id})
.then(user => {
if(user){
return done(null,{
id: user.id,
login: user.login
});
}
return done(null,false);
})
.catch(error => done(error,null));
});
passport.use(strategy);
return {
initialize: () => passport.initialize(),
authenticate: () => passport.authenticate('jwt', jwtConfig.session)
};
}
It would be the same way you’re going through the
'Content-Type': 'application/json'
. In place ofContent-type
would be the header name your API expects to receive from JWT and instead ofapplication/json
will your JWT. Would this be your question?– Marcelo Vismari
Yes it would be, could you answer for me to give the positive vote? In Case: I have this route: app.route('/users') I would have to add a parameter to my auth: . all(app.auth.authenticate()), authenticate: () => Passport.authenticate('jwt', jwtConfig.Session)
– gabriel
I don’t know if I’m doing jwt auth correctly, can I edit the question with the method I use my jwt? If you can give me some hint to improve on the code.
– gabriel