0

我正在尝试使用护照在 KOA2 中进行社交登录。当我尝试在 passport.authenticate() 的帮助下对用户进行身份验证时。它应该被执行并且应该把我带到 fb 登录页面,但没有这样做。即使它显示未找到并且没有抛出任何类型的错误。这是我的代码示例:

应用程序.js

import Koa from 'koa'
import views from 'koa-views'
import serve from 'koa-static'
import rootRoutes from './routes/index'
import userRoutes from './routes/user'
import authConfig from './config/oauth'
import authRoutes from './routes/social'
const app = new Koa()
// trust proxy
app.proxy = true

// sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
const passport = require('koa-passport')
app.keys = ['your-session-secret']
// body parser
const bodyParser = require('koa-bodyparser')
// require('./auth')
app.use(bodyParser())
app.use(convert(session()))

// authentication
app.use(convert(passport.initialize()))
app.use(convert(passport.session()))
app.use(views(`${__dirname}/views`, { extension: 'html' }))
app.use(serve(`${__dirname}/public`))
app.use(authRoutes.routes())
app.use(authRoutes.allowedMethods())
app.use(rootRoutes.routes())
console.log("authRoutes", authRoutes);
app.use(rootRoutes.allowedMethods())
app.use(userRoutes.routes())
app.use(userRoutes.allowedMethods())
app.use(async (ctx, next) => {
  try {
    await next(); // next is now a function, await instead of yield
  } catch (err) {
    ctx.body = { message: err.message };
    ctx.status = err.status || 500;
  }
});
app.listen(1337, () => {
  console.log('Server running at http://localhost:1337 and http://127.0.0.1:1337')
})

export default app

社交.js

import Router from 'koa-router'
const router = new Router()
import authConfig from '../config/oauth'
import passport from 'koa-passport'
var user = { id: 1, username: 'test' }

passport.serializeUser((user, done) => {
  console.log(user)
  done(null, user);
});

passport.deserializeUser((id, done) => {
  (async () => {
    try {
      // const user = await User.findById(id);
      console.log("user", user);
      done(null, user);
    } catch (error) {
        console.log("error")
      done(error);
    }
  })();
});

var LocalStrategy = require('passport-local').Strategy
passport.use(new LocalStrategy(function(username, password, done) {
  console.log("user", user);
  // retrieve user ...
  if (username === 'test' && password === 'test') {
    done(null, user)
  } else {
    done(null, false)
  }
}))

var FacebookStrategy = require('passport-facebook').Strategy
passport.use(new FacebookStrategy({
    clientID: '214873665615110',
    clientSecret: 'f30ba1c22c6fef150c4b8ffae3cbffe4',
    callbackURL: 'http://127.0.0.1:1337/auth/facebook/callback'
  },
  function(token, tokenSecret, profile, done) {
    console.log("profile", profile);
    // retrieve user ...
    done(null, user)
  }
))

var TwitterStrategy = require('passport-twitter').Strategy
passport.use(new TwitterStrategy({
    consumerKey: 'authConfig.twitter.consumerKey',
    consumerSecret: 'authConfig.twitter.consumerSecret',
    callbackURL: 'http://127.0.0.1:' + (process.env.PORT || 1337) + '/auth/twitter/callback'
  },
  function(token, tokenSecret, profile, done) {
    // retrieve user ...
    done(null, user)
  }
))

var GoogleStrategy = require('passport-google-auth').Strategy
passport.use(new GoogleStrategy({
    clientId: 'authConfig.google.clientID',
    clientSecret: 'authConfig.google.clientSecret',
    callbackURL: 'http://127.0.0.1:' + (process.env.PORT || 1337) + '/auth/google/callback'
  },
  function(token, tokenSecret, profile, done) {
    // retrieve user ...
    done(null, user)
  }
))

// import authConfig from '../config/oauth'
router.post('/login', async(ctx, next) => {
  console.log("login");
  await passport.authenticate('local', {
    successRedirect: '/about',
    failureRedirect: '/'
  })
  return next();
})

router.get('/auth/facebook', async(ctx, next) => {
    console.log("call aayi");
    await passport.authenticate('facebook');
    // ctx.body = "aa gaya bhai ";
})

router.get('/auth/facebook/callback', async(ctx, next) => {
    passport.authenticate('facebook', {
        successRedirect: '/about',
        failureRedirect: '/'
    })
})
export default router

oath.js拥有社交插件的凭据。

有趣的问题是,当我使用koa-route而不是koa-router. 它正在工作。

const route = require('koa-route');
app.use(route.get('/auth/facebook',
  passport.authenticate('facebook')
))

app.use(route.get('/auth/facebook/callback',
  passport.authenticate('facebook', {
    successRedirect: '/app',
    failureRedirect: '/'
  })
))

一切都保持不变,仅用于koa-route这两条路线,并且工作正常。

4

2 回答 2

1

天哪,经过这么多的发现,得到了答案。问题在于依赖项。koa-passport 是用@next 标签安装的,npm install koa-passport@next而不是npm install koa-passport@latest

于 2016-12-12T07:30:45.200 回答
0

我可以看到的第一件事是您没有正确地将用户序列化进出会话。尝试将 user._id 序列化为会话,该会话稍后将用于从数据库中检索整个用户。

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

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
done(err, user);
});
于 2016-11-07T14:34:37.123 回答