I've uploaded my app to heroku: https://mystoryheroku.herokuapp.com
Please give it a try yourself to see the problem.
Everything seem to work, untill the website is refreshed.
The JWT token is saved in LocalStorage, but is lost from 'header' after page refresh,
which then 'Access Denied' error is seen.
By pasting : https://mystoryheroku.herokuapp.com to the browser, the token is sent to the header again, untill the next refresh..
Verify Middleware:
const jwt = require('jsonwebtoken')
module.exports = function auth (req, res, next){
const token = req.header('auth-token');
if(!token) return res.status(401).send('Access Denied')
try{
const verified = jwt.verify(token, process.env.JWT_KEY)
req.user = verified;
next();
}catch(err){
res.status(400).send('Invalid Token');
}
}
Some routes examples:
//Get All Stories
storyRoute.route('/').get(verify,function(req, res){
Story.find(function(err, story){
if(err){
console.log(err);
}
else{
res.send(story);
}
});
});
//Get Stories by ID
storyRoute.route('/story/:id').get(verify,(req,res, next)=>{
Story.findById(req.params.id, function(err,story){
if(err){
res.status(500).json({
message: "Story not found!"
})
console.log( "Story not found!")
}
res.status(200).json({story});
});
});
//User Profile
userRoute.get('/profile',verify, (req, res)=> {
res.json({
message: 'Auth successful',
user:req.user
});
});
// User Profile (stories)
userRoute.get('/profile/mystories',verify,(req,res) =>{
Story.find({UserId: req.user._id})
.then(stories => {
res.status(200).json({
Stories:stories
});
});
});
Service examples:
getAllStories(){
const token = localStorage.getItem('id_token');
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'auth-token': token
});
const httpOptions = {
headers: headers
};
return this.http.get(`${this.uri}/stories`,httpOptions)
}
getStoryById(id){
const token = localStorage.getItem('id_token');
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'auth-token': token
});
const httpOptions = {
headers: headers
};
return this.http.get(`${this.uri}/stories/story/${id}`,httpOptions).pipe(map(res => res['story']))
}
getProfile(){
const token = localStorage.getItem('id_token');
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'auth-token': token
});
const httpOptions = {
headers: headers
};
return this.http.get(`${this.uri}/profile`, httpOptions)
};
And so on..
How do I resend the token to the header after each refresh?
Much appreciated!