Use Passport.js Behind Corporate Firewall for Facebook Strategy

孤者浪人 提交于 2019-12-10 10:19:33

问题


I have been able to use node.js and passport.js to connect to Facebook using the GitHub project available at: https://github.com/jaredhanson/passport-facebook/tree/master/examples/login.

Here is the what the app.js code is doing:

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

The code works great if I am just using the internet with no proxy server but if I am behind a corporate firewall then I get the following error:

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) 

Does anyone know how to setup the code above to go through a corporate proxy server for connectivity? I have tried setting the npm configuration properties of proxy, http-proxy and https-proxy but it does not appear to make a difference when I run this application. Any help you can offer would be greatly appreciated. Thank you.


回答1:


Adding this code in /node_moduels/oauth/lib/oauth.js would fix the issue temporarily.

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

Finally, set the httpsProxyAgent to the request options right before _executeRequest gets called like this:

options.agent = httpsProxyAgent



回答2:


Adding

options.agent = httpsProxyAgent

worked for me. But I added it in $workdir\node_modules\oauth\lib\oauth2.js as method _executeRequest exists only there. If you have trouble finding _executeRequest I recommend do full search in node_modules\oauth as I found that method in oauth2.js

Also, don't forget that if you use third party API that you should consider them as well. I use vkAPI SDK, which is basically a wrapper over http_library with handy methods. In that case I would suggest to wrap http_library calls and decorate them for your need. Good way to start here Anyway to set proxy setting in passportjs?




回答3:


oauth2.js does not take in consideration the proxy environment variables when it performed the requests. Blocking the web app to get authenticated (receive the access token and the github user info)

So I tried with this workarround that let know to the oauth2.js that uses the proxy to communicate.

You usually will find the oauth2.js code that needs to adapt at: 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) {

...


来源:https://stackoverflow.com/questions/33639337/use-passport-js-behind-corporate-firewall-for-facebook-strategy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!