【问题标题】:Use Passport.js Behind Corporate Firewall for Facebook Strategy在企业防火墙后面使用 Passport.js 实现 Facebook 策略
【发布时间】:2016-02-11 21:10:27
【问题描述】:

我已经能够使用 node.js 和 passport.js 通过 GitHub 项目连接到 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.js proxy passport.js


    【解决方案1】:

    /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
    

    【讨论】:

    • 我能找到的唯一 oauth.js 位于 \node_modules\passport-facebook\node_modules\passport-oauth2\node_modules\oauth\lib\oauth.js 中。代码中没有 _executeRequest 只是一个 _performSecureRequest 方法。这是您应该放置上面列出的 HttpsProxyAgent 代码的地方吗?此外,我没有看到任何选项对象来设置代理值。应该使用什么对象?谢谢。
    【解决方案2】:

    oauth2.js 在执行请求时不考虑代理环境变量。阻止 Web 应用进行身份验证(接收访问令牌和 github 用户信息)

    所以我尝试了这个 workarround,让 oauth2.js 知道使用代理进行通信。

    您通常会在以下位置找到需要适配的 oauth2.js 代码:your_project/node_modules/oauth/lib/oauth2.js

    var querystring= require('querystring'),
        crypto= require('crypto'),
        https= require('https'),
        http= require('http'),
        URL= require('url'),
        OAuthUtils= require('./_utils');
    
    // line codes to add
    var HttpsProxyAgent = require('https-proxy-agent');
    let httpsProxyAgent = null
    
    if (process.env['https_proxy']) {
        httpsProxyAgent = new HttpsProxyAgent("http://127.0.0.1:1087");
        // fill in your proxy agent ip and port
    }
    
    ....
      // line codes to add
      options.agent = httpsProxyAgent;
    
      this._executeRequest( http_library, options, post_body, callback );
    }
    
    exports.OAuth2.prototype._request= function(method, url, headers, post_body, access_token, callback) {
    
    ...
    

    【讨论】:

    • 抱歉,但这让我很困惑,因为在要添加的第二行代码块上似乎有一个外围大括号。我应该摆脱它吗?或者它可能直接进入到该 sn-p 底部的出口的正上方...?
    【解决方案3】:

    添加

    options.agent = httpsProxyAgent
    

    为我工作。但是我在 $workdir\node_modules\oauth\lib\oauth2.js 中添加了它,因为方法 _executeRequest 只存在于那里。 如果您在查找 _executeRequest 时遇到问题,我建议您在 node_modules\oauth 中进行完整搜索,因为我在 oauth2.js 中找到了该方法

    另外,不要忘记,如果您使用第三方 API,您也应该考虑使用它们。我使用 vkAPI SDK,它基本上是 http_library 的包装器,带有方便的方法。 在这种情况下,我建议包装http_library 电话并根据您的需要装饰它们。 从这里开始的好方法Anyway to set proxy setting in passportjs?

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 2019-02-07
      • 1970-01-01
      • 2020-10-24
      • 2017-11-29
      • 2015-09-17
      • 1970-01-01
      • 2013-12-10
      相关资源
      最近更新 更多