4

認証方法としてjsonwebtokenを使用してノードエクスプレスRESTful APIを作成しました。ただし、Angular js を使用して x-access-token をヘッダーとして渡すことはできません。

私のJWTトークン認証スクリプトは、

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





            }       

        }

    });
});

トークンが正しいかチェックするミドルウェアは、

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

    }

});

最後にGETメソッドのスクリプトは、

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



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

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

しかし、それは常に認証に失敗しました。この問題を解決するために私を助けてください。私は本当にここで立ち往生しています。

次の認証失敗メッセージのみが常に表示されます。

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

3 に答える 3

6

angularコントローラーの依存関係として $http を使用する場合、これは私が推測するのに役立ちます-

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

angularコードをアップロードしたら、コードに従ってこれを変更します。

于 2016-04-27T11:16:16.880 に答える