Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InternalOAuthError: Failed to obtain access token

Can anyone help me with what is wrong with the below code in the link GitHub oauth2-provider server with passport-oauth2 consumer

After I login with http://localhost:8082 and reach my callback URL: http://localhost:8081/auth/provider/callback, it throws an error

var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , TwitterStrategy = require('passport-twitter').Strategy;

var TWITTER_CONSUMER_KEY = "--insert-twitter-consumer-key-here--";
var TWITTER_CONSUMER_SECRET = "--insert-twitter-consumer-secret-here--";

passport.serializeUser(function(user, done) {
  done(null, user);
});

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

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      return done(null, profile);
    });
  }
));


var app = express.createServer();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  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 });
});

app.get('/auth/twitter',
  passport.authenticate('twitter'),
  function(req, res){
    // The request will be redirected to Twitter for authentication, so this
    // function will not be called.
  });

app.get('/auth/twitter/callback', 
  passport.authenticate('twitter', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

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

app.listen(3000);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
} 

InternalOAuthError: Failed to obtain access token

How can I resolve this issue?

like image 443
user3180402 Avatar asked Jan 15 '14 05:01

user3180402


3 Answers

I ran into a similar issue trying to get passport-oauth2 working. The error message, as you've observed, is less than helpful:

InternalOAuthError: Failed to obtain access token
    at OAuth2Strategy._createOAuthError (node_modules/passport-oauth2/lib/strategy.js:382:17)
    at node_modules/passport-oauth2/lib/strategy.js:168:36
    at node_modules/oauth/lib/oauth2.js:191:18
    at ClientRequest.<anonymous> (node_modules/oauth/lib/oauth2.js:162:5)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)

I found a suggestion to make a small change to passport-oauth2:

--- a/lib/strategy.js
+++ b/lib/strategy.js
@@ -163,7 +163,10 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {

    self._oauth2.getOAuthAccessToken(code, params,
        function(err, accessToken, refreshToken, params) {
-          if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }
+          if (err) {
+            console.warn("Failed to obtain access token: ", err);
+            return self.error(self._createOAuthError('Failed to obtain access token', err));
+          }

Once I did that, I got a much more helpful error message:

Failed to obtain access token:  { Error: self signed certificate
    at TLSSocket.<anonymous> (_tls_wrap.js:1103:38)
    at emitNone (events.js:106:13)
    at TLSSocket.emit (events.js:208:7)
    at TLSSocket._finishInit (_tls_wrap.js:637:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:467:38) code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }

In my case I believe the root cause was that the authorization server I was testing with was using a self-signed SSL cert, which I was able to work around by adding this line:

require('https').globalAgent.options.rejectUnauthorized = false;
like image 145
bmaupin Avatar answered Nov 17 '22 02:11

bmaupin


same here I got the same issue. Finally I found a solution is related with the corporate proxy and you can check it out the workaround here

like image 39
Victor R Hdez Avatar answered Nov 17 '22 04:11

Victor R Hdez


For anyone still struggling with this, there's an issue in the node-oauth package mentioned here.

Basically, on faster connections, node-oauth receives ECONNRESET and triggers the provided callback twice. A quick way to fix this is to add a single line to node_modules/oauth/lib/oauth2.js near line 161 inside the error listener:

   request.on('error', function(e) {
     if (callbackCalled) { return }  // Add this line
     callbackCalled= true;
     callback(e);
   });

There's already a PR from November, 2021 concerning this issue but it has not been merged. It seems like node-oauth is no longer being maintained. I lost past 2 working days scratching my head on this problem. Hoping you guys find this answer.

EDIT: The PR has been merged as of 23th July 2022, but the dependency versions haven't been updated in passport-oauth2 and passport-google-oauth2. Here are corresponding issues to follow: passport-oauth2 issue and passport-google-oauth2 issue

like image 2
Mythos Avatar answered Nov 17 '22 04:11

Mythos