node.js - 内部 OAuthError : Failed to obtain access token

标签 node.js authentication oauth authorization

谁能帮我解决链接GitHub中的以下代码有什么问题? oauth2-provider 服务器和 passport-oauth2 消费者

在我使用 http://localhost:8082 登录并到达我的回调 URL 后: http://localhost:8081/auth/provider/callback,会报错

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

我该如何解决这个问题?

最佳答案

我在尝试让 passport-oauth2 工作时遇到了类似的问题。正如您所观察到的,该错误消息没有多大帮助:

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)

我找到了 a suggestion对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));
+          }

一旦我这样做了,我会收到一条更有帮助的错误消息:

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

在我的情况下,我认为根本原因是我正在测试的授权服务器使用的是自签名 SSL 证书,我可以通过添加以下行来解决这个问题:

require('https').globalAgent.options.rejectUnauthorized = false;

关于node.js - 内部 OAuthError : Failed to obtain access token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21129989/

相关文章:

javascript - npm 脚本,打包时将 package.json 复制到 dist

node.js - Node Express 4 中的路由器

php - nginx:auth_basic 和 php

java - 使用 Spring Security 登录后无法重定向到不同页面

rest - 为移动应用程序创建 API - 身份验证和授权

node.js - 如何在本地使用 grunt 在生产模型中运行 Mean.JS

api - 如何使用 redirect_uri (callback.html) 验证 Soundcloud API

node.js - 使用 Node.js 保护 API

ios - 与 parse-server 和 auth0 的自定义身份验证集成

node.js - 如何在stripe.js中创建支付意图时传递客户端IP地址