2016-08-27 79 views
0

我正在使用http-bearer策略處理OAuth令牌的Passport身份驗證。這裏是我的策略:如何將令牌傳遞給此函數?

var passport = require('passport'), 
    url = require('url'), 
    BearerStrategy = require('passport-http-bearer').Strategy, 
    config = require('../config'), 
    mongoose = require('mongoose'), 
    User = mongoose.model('User'), 
    users = require('../../app/controllers/users.server.controller'); 

module.exports = function() { 
    // Use bearer strategy 
    passport.use(new BearerStrategy(
     function(token, done) { 

      User.findOne({ token: token }, function (err, user) { 
       if (err) { return done(err); } 
       if (!user) { return done(null, false); } 
       return done(null, user, { scope: 'all' }); 
      }); 
     } 
    )); 
}; 

這裏是我的快遞路線:

app.route('/auth/bearersignin').post(users.bearerSignin); 

這是我的exports.module:

exports.bearerSignin = function(req, res) { 
    console.log('bearerSignin', req.user); 
    passport.authenticate('bearer', { 
     session: false 
    })(req, res, function() { // this is the function called after auth 
     console.log('inside authenticate', req.user); 
     var response = { 
      userObj: req.user, 
      redirectUrl: req.session.redirectUrl 
     }; 
     res.json(response); 
    }); 
}; 

有問題的令牌這裏埋在req.user對象根據req.user.twitter.token:

{ 
    _id: abc123idnumber, 
    photo: 'https://pbs.twimg.com/profile_images/abc123/IMG_2899-square_normal.jpg', 
    provider: 'local', 
    username: 'userabc123', 
    __v: 0, 
    created: Tue Aug 23 2016 00:52:20 GMT+0000 (UTC), 
    updated: Fri Aug 26 2016 03:53:17 GMT+0000 (UTC), 
    freeEventsCount: 1, 
    eventsSubscription: false, 
    profiles: [], 
    roles: [ 'user' ], 
    google: {}, 
    facebook: {}, 
    twitter: 
    { profilePhoto: 'https://pbs.twimg.com/profile_images/idabc123/square_normal.jpg', 
     name: 'Joe Smith', 
     token: 'tokenabc123', 
     username: 'tonejac', 
     id: 'abc123' }, 
    localAccountExists: true, 
    firstName: 'joe', 
    email: '[email protected]' 
} 

我如何將令牌值傳遞給護照。驗證上面的'載體'功能?

回答

1

你需要在你的http post調用中設置headers

headers : {'Authorization' : 'Bearer yourtoken'} 

如果您正在使用角JS,你可以試試這個:

var req = { 
method: 'POST', 
url: 'http://example.com', 
headers: { 
    'Authorization': 'Bearer '+ token 
}, 
data: { test: 'test' } 
} 

$http(req).then(function(){...}, function(){...}); 

有關HTTP調用的更多信息,請參閱AngularJs $http documentation

我希望這可以幫助你。