0

我目前正在开发一个需要通过战网 oauth 流从用户登录获取访问令牌的应用程序。我正在使用来自 npm的 passport-bnet,但是在让它工作时遇到了一些问题(我使用的是 fastify 而不是 express)。我想找到错误,所以我从passport-bnet 存储库中克隆了示例。当然,我添加了所需的 env 值(id 和 secret),但身份验证总是失败

InternalOAuthError:无法获取用户 ID 错误(重定向到 /bnet/callback 总是等待几秒钟,然后返回错误)。

整个代码看起来像这样

var express = require('express');
var passport = require('passport');
var util = require('util');
var fs = require('fs');
var https = require('https');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var BnetStrategy = require('passport-bnet').Strategy;

var BNET_ID = '...';
var BNET_SECRET = '...';

var privateKey  = fs.readFileSync('server.key', 'utf8');
var certificate = fs.readFileSync('server.cert', 'utf8');

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

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


// Use the BnetStrategy within Passport.
passport.use(
  new BnetStrategy(
    { clientID: BNET_ID,
      clientSecret: BNET_SECRET,
      scope: "wow.profile",
      callbackURL: "https://localhost:3000/auth/bnet/callback" },
    function(accessToken, refreshToken, profile, done) {
      process.nextTick(function () {
        return done(null, profile);
      });
    })
);

var app = express();

// configure Express
app.use(cookieParser());
app.use(session({ secret: 'blizzard',
                  saveUninitialized: true,
                  resave: true }));

// Initialize Passport!  Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/bnet',
        passport.authenticate('bnet'));

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

app.get('/', function(req, res) {
  if(req.isAuthenticated()) {
    var output = '<h1>Express OAuth Test</h1>' + req.user.id + '<br>';
    if(req.user.battletag) {
      output += req.user.battletag + '<br>';
    }
    output += '<a href="/logout">Logout</a>';
    res.send(output);
  } else {
    res.send('<h1>Express OAuth Test</h1>' +
             '<a href="/auth/github">Login with Github</a><br>' +
             '<a href="/auth/bnet">Login with Bnet</a>');
  }
});

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

var credentials = {key: privateKey, cert: certificate};
var httpsServer = https.createServer(credentials, app);

var server = httpsServer.listen(3000, function() {
  console.log('Listening on port %d', server.address().port);
});

我什至尝试添加一个自签名证书并在启用 https 的情况下运行 express。真的不知道我是否做错了什么,我还没有找到与此类似的问题已解决。感谢您的帮助,谢谢。

4

0 回答 0