Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."}
like image 423
LearnCode Master Avatar asked Mar 12 '23 11:03

LearnCode Master


2 Answers

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.

like image 62
Sk Arif Avatar answered Mar 15 '23 01:03

Sk Arif


The client should be sending the token in the Authorization header, using the Bearer scheme, as 'X-' headers have been deprecated since 2012:

Your node would now be along the lines of:

apps.post('/authenticate', function(req, res) { 
    .....
    var token = 'Bearer' + ' ' + jwt.sign(item, app.get('superSecret'), {
        expiresIn: 86400 // expires in 24 hours
    });
    .....
 }

apps.use(function(req, res, next) {
    // Trim out the bearer text using substring
    var token = req.get('Authorization').substring(7);
    ....
}

Then your angular code would become:

var token = this.AuthToken.getToken();
$http.get('/api/me', { headers: {'Authorization': token} });
like image 41
mattyb Avatar answered Mar 14 '23 23:03

mattyb