如何在使用 passportjs 进行身份验证后对数据发出 oauth 请求?
How to make a oauth request for data after authentication with passportjs?
我正在尝试创建一个 NodeJS 应用程序,它从 Twitter 用户配置文件中提取数据,例如获取关注者、发布推文等。
为了对应用程序进行身份验证,我使用了passport-js提供的身份验证方法(twitter策略):http://passportjs.org/
身份验证策略是通过为 Twitter 身份验证创建策略,然后使用该策略对 Twitter 进行身份验证来完成的,大致如下:
// =========================================================================
// TWITTER LOGIN =================================================================
// =========================================================================
passport.use(new TwitterStrategy({
consumerKey : twitterAuth.consumerKey,
consumerSecret : twitterAuth.consumerSecret,
callbackURL : twitterAuth.callbackURL,
passReqToCallback : true, // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, tokenSecret, profile, done) {
// User.findOne won't fire until we have all our data back from Twitter
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
console.log("Twitter Check if user is already logged in");
User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);
// if the user is found then log them in
if (user) {
console.log("Twitter User has been found log him in");
// if there is a user id already but no token (user was linked at one point and then removed)
// just add our token and profile information
if (!user.twitter.token) {
console.log("Twitter, user was linked and then removed, add back token");
user.twitter.id = profile.id;
user.twitter.token = token;
user.twitter.tokenSecret = tokenSecret;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
return done(null, user); // user found, return that user
}));
// ==============================
在此之后,我可以使用如下策略进行身份验证:
// =====================================
// TWITTER ROUTES ======================
// =====================================
// route for twitter authentication and login
app.get('/auth/twitter', passport.authenticate('twitter'));
// handle the callback after twitter has authenticated the user
app.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect : '/dashboard',
failureRedirect : '/'
}));
身份验证工作正常,我从用户那里收到令牌和 tokensecret,可以将其保存在我的会话中。但是,现在我想为用户做其他请求,例如获取关注者和发帖等,但我真的不明白该怎么做。
我可以在不使用 passportJS 的情况下使用 oauth 沿着这些线路毫无问题地发一条推文,例如:
// Authentication using oauth for Twitter
var username = 'user';
var oa = require('oauth').OAuth();
oa = new OAuth("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"consumerkey", "consumersecret",
"1.0A", "http://localhost:3000/oauth/authenticate", "HMAC-SHA1");
var access_token= "access_token";
var access_token_secret= "access_token_secret";
// Test if user has been authenticated
oa.get("https://api.twitter.com/1.1/users/show.json?screen_name=" + user, access_token, access_token_secret, function(error, data) {
if (!error)
console.log(data);
else
console.log("An error has occurred while authentication of the user: " + error);
});
console.log("Twitter-API Successfully Loaded");
// Use Oauth to post a tweet
// Tweet a post update
router.post('/post-tweet/', function (req, res) {
oa.post("https://api.twitter.com/1.1/statuses/update.json?status=" + req.body.tweet, access_token, access_token_secret, {}, "", function(error, data) {
if (!error && res.statusCode == 200){
res.send("Successfully tweeted an update");
}
else {
res.send("Failure to tweet a new post: " + JSON.stringify(error));
}
});
});
现在基本上我的问题是,如何使用 passportJS 做完全相同的事情???我不明白如何从 passportJS 获得身份验证机制,以便能够向 Twitter API 发出 GET 或 POST 请求。
编辑:
我找到了我需要的护照对象并且可以访问它,但是,我如何检索 Twitter 详细信息中的 _oauth 对象?
对象内容如下:
Authenticator {
_key: 'passport',
_strategies:
{ session: SessionStrategy { name: 'session' },
'local-signup':
Strategy {
_usernameField: 'email',
_passwordField: 'password',
name: 'local',
_verify: [Function],
_passReqToCallback: true },
'local-login':
Strategy {
_usernameField: 'email',
_passwordField: 'password',
name: 'local',
_verify: [Function],
_passReqToCallback: true },
facebook:
Strategy {
name: 'facebook',
_verify: [Function],
_oauth2: [Object],
_callbackURL: 'http://localhost:3000/auth/callback',
_scope: undefined,
_scopeSeparator: ',',
_key: 'oauth2:www.facebook.com',
_stateStore: NullStore {},
_trustProxy: undefined,
_passReqToCallback: true,
_skipUserProfile: false,
_profileURL: 'https://graph.facebook.com',
_profileFields: [Object],
_enableProof: undefined,
_clientSecret: '012345' },
twitter:
Strategy {
name: 'twitter',
_verify: [Function],
>> _oauth: [Object], I would need this object here
_userAuthorizationURL: 'https://api.twitter.com/oauth/authenticate',
_callbackURL: 'http://localhost:3000/auth/twitter/callback',
_key: 'oauth:twitter',
_requestTokenStore: [Object],
_trustProxy: undefined,
_passReqToCallback: true,
_skipUserProfile: false,
_userProfileURL: 'https://api.twitter.com/1.1/account /verify_credentials.json',
_skipExtendedUserProfile: false,
_includeEmail: false,
_includeStatus: true,
_includeEntities: true } },
_serializers: [ [Function] ],
_deserializers: [ [Function] ],
_infoTransformers: [],
_framework:
{ initialize: [Function: initialize],
authenticate: [Function: authenticate] },
_userProperty: 'user',
Authenticator: [Function: Authenticator],
Passport: [Function: Authenticator],
Strategy: { [Function: Strategy] Strategy: [Circular] },
strategies: { SessionStrategy: { [Function: SessionStrategy] super_: [Object] } } }
好的,我修好了:)
对于遇到同样问题的人,在护照中访问oauth的方法是:
passport._strategies.twitter._oauth.post(一些动作){
}
我正在尝试创建一个 NodeJS 应用程序,它从 Twitter 用户配置文件中提取数据,例如获取关注者、发布推文等。 为了对应用程序进行身份验证,我使用了passport-js提供的身份验证方法(twitter策略):http://passportjs.org/
身份验证策略是通过为 Twitter 身份验证创建策略,然后使用该策略对 Twitter 进行身份验证来完成的,大致如下:
// =========================================================================
// TWITTER LOGIN =================================================================
// =========================================================================
passport.use(new TwitterStrategy({
consumerKey : twitterAuth.consumerKey,
consumerSecret : twitterAuth.consumerSecret,
callbackURL : twitterAuth.callbackURL,
passReqToCallback : true, // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, tokenSecret, profile, done) {
// User.findOne won't fire until we have all our data back from Twitter
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
console.log("Twitter Check if user is already logged in");
User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);
// if the user is found then log them in
if (user) {
console.log("Twitter User has been found log him in");
// if there is a user id already but no token (user was linked at one point and then removed)
// just add our token and profile information
if (!user.twitter.token) {
console.log("Twitter, user was linked and then removed, add back token");
user.twitter.id = profile.id;
user.twitter.token = token;
user.twitter.tokenSecret = tokenSecret;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
return done(null, user); // user found, return that user
}));
// ==============================
在此之后,我可以使用如下策略进行身份验证:
// =====================================
// TWITTER ROUTES ======================
// =====================================
// route for twitter authentication and login
app.get('/auth/twitter', passport.authenticate('twitter'));
// handle the callback after twitter has authenticated the user
app.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect : '/dashboard',
failureRedirect : '/'
}));
身份验证工作正常,我从用户那里收到令牌和 tokensecret,可以将其保存在我的会话中。但是,现在我想为用户做其他请求,例如获取关注者和发帖等,但我真的不明白该怎么做。
我可以在不使用 passportJS 的情况下使用 oauth 沿着这些线路毫无问题地发一条推文,例如:
// Authentication using oauth for Twitter
var username = 'user';
var oa = require('oauth').OAuth();
oa = new OAuth("https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
"consumerkey", "consumersecret",
"1.0A", "http://localhost:3000/oauth/authenticate", "HMAC-SHA1");
var access_token= "access_token";
var access_token_secret= "access_token_secret";
// Test if user has been authenticated
oa.get("https://api.twitter.com/1.1/users/show.json?screen_name=" + user, access_token, access_token_secret, function(error, data) {
if (!error)
console.log(data);
else
console.log("An error has occurred while authentication of the user: " + error);
});
console.log("Twitter-API Successfully Loaded");
// Use Oauth to post a tweet
// Tweet a post update
router.post('/post-tweet/', function (req, res) {
oa.post("https://api.twitter.com/1.1/statuses/update.json?status=" + req.body.tweet, access_token, access_token_secret, {}, "", function(error, data) {
if (!error && res.statusCode == 200){
res.send("Successfully tweeted an update");
}
else {
res.send("Failure to tweet a new post: " + JSON.stringify(error));
}
});
});
现在基本上我的问题是,如何使用 passportJS 做完全相同的事情???我不明白如何从 passportJS 获得身份验证机制,以便能够向 Twitter API 发出 GET 或 POST 请求。
编辑: 我找到了我需要的护照对象并且可以访问它,但是,我如何检索 Twitter 详细信息中的 _oauth 对象?
对象内容如下:
Authenticator {
_key: 'passport',
_strategies:
{ session: SessionStrategy { name: 'session' },
'local-signup':
Strategy {
_usernameField: 'email',
_passwordField: 'password',
name: 'local',
_verify: [Function],
_passReqToCallback: true },
'local-login':
Strategy {
_usernameField: 'email',
_passwordField: 'password',
name: 'local',
_verify: [Function],
_passReqToCallback: true },
facebook:
Strategy {
name: 'facebook',
_verify: [Function],
_oauth2: [Object],
_callbackURL: 'http://localhost:3000/auth/callback',
_scope: undefined,
_scopeSeparator: ',',
_key: 'oauth2:www.facebook.com',
_stateStore: NullStore {},
_trustProxy: undefined,
_passReqToCallback: true,
_skipUserProfile: false,
_profileURL: 'https://graph.facebook.com',
_profileFields: [Object],
_enableProof: undefined,
_clientSecret: '012345' },
twitter:
Strategy {
name: 'twitter',
_verify: [Function],
>> _oauth: [Object], I would need this object here
_userAuthorizationURL: 'https://api.twitter.com/oauth/authenticate',
_callbackURL: 'http://localhost:3000/auth/twitter/callback',
_key: 'oauth:twitter',
_requestTokenStore: [Object],
_trustProxy: undefined,
_passReqToCallback: true,
_skipUserProfile: false,
_userProfileURL: 'https://api.twitter.com/1.1/account /verify_credentials.json',
_skipExtendedUserProfile: false,
_includeEmail: false,
_includeStatus: true,
_includeEntities: true } },
_serializers: [ [Function] ],
_deserializers: [ [Function] ],
_infoTransformers: [],
_framework:
{ initialize: [Function: initialize],
authenticate: [Function: authenticate] },
_userProperty: 'user',
Authenticator: [Function: Authenticator],
Passport: [Function: Authenticator],
Strategy: { [Function: Strategy] Strategy: [Circular] },
strategies: { SessionStrategy: { [Function: SessionStrategy] super_: [Object] } } }
好的,我修好了:)
对于遇到同样问题的人,在护照中访问oauth的方法是: passport._strategies.twitter._oauth.post(一些动作){ }