4

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."}
2
  • did you search that before and what did you get? Commented Apr 27, 2016 at 10:15
  • @jicks Can you please show your angular route? Commented Apr 27, 2016 at 10:52

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

But its not fully angular code. I used angular js script in node js for the purpose of passing x-access-token as header.
You can read this article - using-json-web-tokens-node-js. I think it will help you getting some information about what you are looking for.
Still i didnt get any idea about how to pass header.@Sk Arif
1

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

1 Comment

Not all heroes wear cape, but is this the new way moving forward?
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.