jicks jicks - 1 month ago 15
AngularJS Question

How to pass JsonWebToken x-access-token through angular js

I created a node express RESTful API with jsonwebtoken as authentication method. But unable to pass the x-access-token as headers using angular js.

my JWT token authentication script is,

apps.post('/authenticate', function(req, res) {

// find the item
Item.findOne({
name: req.body.name
}, function(err, item) {

if (err) throw err;

if (!item)
{
res.json({ success: false, message: 'Authentication failed. item not found.' });
}
else if (item)
{

// check if password matches
if (item.password != req.body.password)
{
res.json({ success: false, message: 'Authentication failed. Wrong password.' });
}
else
{

// if item is found and password is right
// create a token
var token = jwt.sign(item, app.get('superSecret'), {
expiresIn: 86400 // expires in 24 hours
});



res.json({
success: true,
message: 'Enjoy your token!',
token: token
});





}

}

});
});


Middleware which checks the token is correct is,

apps.use(function(req, res, next) {

// check header or url parameters or post parameters for token
var token = req.body.token || req.params.token || req.headers['x-access-token'];

// decode token
if (token)
{

// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err)
{
return res.json({ success: false, message: 'Failed to authenticate token.' });
}
else
{
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});

}
else
{

// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});

}

});


Finally the GET method script is,

app.get('/display', function(req, res) {
Item.find({}, function(err, items) {



$http.defaults.headers.common['X-Access-Token']=token;

res.json(items);
});
});


But it always failed to authenticate. Please any one help me to solve this issue. I am really stucked here.

It always shows only the following authentication failed message.

{"success":false,"message":"No token provided."}

Answer

If you use $http as the dependency in your angular controller then this would help you I guess -

var token = this.AuthToken.getToken();
$http.get('/api/me', { headers: {'x-access-token': token} });

I will change this according to your code once you upload your angular code.

Comments