LearnCode Master
LearnCode Master

Reputation: 552

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."}

Upvotes: 4

Views: 16188

Answers (3)

jaredmahan
jaredmahan

Reputation: 86

You could create a interceptor that catches all ajax calls and injects the token into the header. That way you would not have inject it every time you make an ajax call.

This is a good place to start if you wanted to go that route: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

Upvotes: 0

mattyb
mattyb

Reputation: 1161

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} });

Upvotes: 1

Sk Arif
Sk Arif

Reputation: 1120

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.

Upvotes: 6

Related Questions