Discord OAuth2使用koa

时间:2018-03-17 06:53:02

标签: node.js oauth-2.0 passport.js koa koa-passport

我试图使用koa和护照登录不和。

我使用了koa-passportpassport-discord的示例,但不知怎的,我无法让它发挥作用。似乎它的大部分都有效(我得到了accessToken,refreshToken和个人资料信息),但是在身份验证永远不会发生之后重定向,页面只显示Not Found

使用快递,一切正常。

我认为这个错误在某处,但是我尝试了所有内容并且无法使其发挥作用。

router.get('/auth/discord/callback', passport.authenticate('discord', {
  scope: scopes,
  failureRedirect: '/'
}, (err, profile, info) => {
  console.log(err, profile, info);
}), (ctx, next) => {
  console.log('test'); // never executed
});

在koa,第二个中间件并没有被执行,而在表达它时。但是查看koa-router文档,看起来应该是这样。

这是我的完整代码:

server.js

const Koa = require('koa')
const app = new Koa()
const scopes = ['identify', 'guilds'];

// trust proxy
app.proxy = true

// sessions
const session = require('koa-session')
app.keys = ['your-session-secret']
app.use(session({}, app))

// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

// authentication
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())

// routes
const fs = require('fs')
const Router = require('koa-router');

const router = new Router();

app.use((ctx, next) => {
  console.log('url', ctx.url);
  next();
});

router.get('/', function (ctx) {
  ctx.type = 'html'
  ctx.body = fs.createReadStream('server/views/login.html')
})

router.get('/logout', function (ctx) {
  ctx.logout()
  ctx.redirect('/')
})

router.get('/auth/discord', passport.authenticate('discord', {
  scope: scopes
}));
router.get('/auth/discord/callback', passport.authenticate('discord', {
  scope: scopes,
  failureRedirect: '/'
}, (err, profile, info) => {
  console.log(err, profile, info);
}), (ctx, next) => {
  console.log('test'); // never executed
});

// Require authentication for now
app.use(function (ctx, next) {
  if (ctx.isAuthenticated()) {
    return next()
  } else {
    ctx.redirect('/')
  }
})

router.get('/app', function (ctx) {
  ctx.type = 'html'
  ctx.body = fs.createReadStream('server/views/app.html')
})

app.use(router.routes());

// start server
const port = process.env.PORT || 3000
app.listen(port, () => console.log('Server listening on', port))

auth.js

const passport = require('koa-passport')
const configWeb = require('../config_web.json');
const scopes = ['identify', 'guilds'];

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

passport.deserializeUser(async function (id, done) {
  try {
    done(null, {
      id: 1,
      username: 'test'
    })
  } catch (err) {
    done(err)
  }
})

var DiscordStrategy = require('passport-discord').Strategy;

passport.use(new DiscordStrategy({
    clientID: configWeb.discordClientID,
    clientSecret: configWeb.discordClientSecret,
    callbackURL: 'http://localhost:3000/auth/discord/callback',
    scopes: scopes
  },
  function (accessToken, refreshToken, profile, done) {
    console.log(accessToken, refreshToken, profile);
    return done(null, profile);
  }));

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我一直在尝试使用与您相同的模块,感谢您共享您的代码,因为它帮助我填补了所有这些模块的文档之间的空白。

我自己玩了之后,我认为问题出在这里:

router.get('/auth/discord/callback', passport.authenticate('discord', {
  scope: scopes,
  failureRedirect: '/'
}, (err, profile, info) => {
  console.log(err, profile, info);
}), (ctx, next) => {
  console.log('test'); // never executed
});

在遵循this SO answer之后,我尝试更改该路线以使其工作如下:

router.get('/auth/discord/callback', async ctx => {
    return passport.authenticate('discord', {scope: scopes, failureRedirect: '/'},
    function(err, user, info, status) {
        console.log('test'); // This gets executed.
        // And now the ctx object is in-scope to be used from the passport callback.
        ctx.redirect('/');
    })(ctx);
});