node.js - 在公司防火墙后面使用 Passport.js 实现 Facebook 战略

标签 node.js proxy passport.js

我已经能够通过 GitHub 项目使用 node.js 和 passport.js 连接到 Facebook:https://github.com/jaredhanson/passport-facebook/tree/master/examples/login .

这是 app.js 代码的作用:

var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , FacebookStrategy = require('passport-facebook').Strategy
  , logger = require('morgan')
  , session = require('express-session')
  , bodyParser = require("body-parser")
  , cookieParser = require("cookie-parser")
  , methodOverride = require('method-override');

var FACEBOOK_APP_ID = "--insert-facebook-app-id-here--"
var FACEBOOK_APP_SECRET = "--insert-facebook-app-secret-here--";


// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.  However, since this example does not
//   have a database of user records, the complete Facebook profile is serialized
//   and deserialized.
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


// Use the FacebookStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Facebook
//   profile), and invoke a callback with a user object.
passport.use(new FacebookStrategy({
    clientID: FACEBOOK_APP_ID,
    clientSecret: FACEBOOK_APP_SECRET,
    callbackURL: "http://localhost:3000/auth/facebook/callback"
  },
  function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // To keep the example simple, the user's Facebook profile is returned to
      // represent the logged-in user.  In a typical application, you would want
      // to associate the Facebook account with a user record in your database,
      // and return that user instead.
      return done(null, profile);
    });
  }
));




var app = express();

// configure Express
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(logger());
  app.use(cookieParser());
  app.use(bodyParser());
  app.use(methodOverride());
  app.use(session({ secret: 'keyboard cat' }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static(__dirname + '/public'));


app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

// GET /auth/facebook
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Facebook authentication will involve
//   redirecting the user to facebook.com.  After authorization, Facebook will
//   redirect the user back to this application at /auth/facebook/callback
app.get('/auth/facebook',
  passport.authenticate('facebook'),
  function(req, res){
    // The request will be redirected to Facebook for authentication, so this
    // function will not be called.
  });

// GET /auth/facebook/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.listen(3000);


// Simple route middleware to ensure user is authenticated.
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

如果我只是在没有代理服务器的情况下使用互联网,那么代码工作得很好,但如果我在公司防火墙后面,那么我会收到以下错误:

InternalOAuthError: Failed to obtain access token
   at Strategy.OAuth2Strategy._createOAuthError (C:\FacebookExample\passport-facebook\examples\login\node_modules\passport-facebook\node_modules\passport-oauth2\lib\strategy.js:348:17)
   at C:\FacebookExample\passport-facebook\examples\login\node_modules\passport-facebook\node_modules\passport-oauth2\lib\strategy.js:171:43
   at C:\FacebookExample\passport-facebook\examples\login\node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:177:18
   at ClientRequest.<anonymous> (C:\FacebookExample\passport-facebook\examples\login\node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:148:5)
   at emitOne (events.js:77:13)
   at ClientRequest.emit (events.js:169:7)
   at TLSSocket.socketErrorListener (_http_client.js:259:9)
   at emitOne (events.js:77:13)
   at TLSSocket.emit (events.js:169:7)
   at emitErrorNT (net.js:1253:8) 

有谁知道如何设置上面的代码以通过公司代理服务器进行连接?我已经尝试设置代理、http-proxy 和 https-proxy 的 npm 配置属性,但是当我运行这个应用程序时它似乎没有什么不同。您能提供的任何帮助将不胜感激。谢谢。

最佳答案

/node_moduels/oauth/lib/oauth.js 中添加这段代码可以暂时解决这个问题。

var HttpsProxyAgent = require('https-proxy-agent');
if (process.env['https_proxy']) {
  httpsProxyAgent = new HttpsProxyAgent(process.env['https_proxy']);
}

最后,在 _executeRequest 被调用之前将 httpsProxyAgent 设置为请求选项:

options.agent = httpsProxyAgent

关于node.js - 在公司防火墙后面使用 Passport.js 实现 Facebook 战略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33639337/

相关文章:

javascript - Node JS - 从同一文件中的另一个方法调用一个方法

asp.net-core - 使用 ASPNET Core 2 从企业代理后面通过 Azure AD 进行身份验证

node.js - 使用 Jasmine 测试 Express/Passport 中间件——passport.authenticate 永远不会完成

node.js - Node.js 请求导致 SOCKS 连接失败

通过 HTTP 代理进行 iOS XMPP 聊天

typescript - 如何诊断passport.authenticate?

node.js - Passport.js Passport-twitter.js Node.js 奇怪的 500 错误

javascript - NodeJs 对每个返回的 MySql 结果对象执行操作

带有 ES6 模块、Typescript 和 Winston 的 node.js : "error TS2307: Cannot find module ' winston'"

javascript - Node.js:导出模块不起作用