passport.authenticate 根本不工作
passport.authenticate is not working at all
我正在尝试使用护照在 KOA2 中进行社交登录。当我尝试在 passport.authenticate() 的帮助下对用户进行身份验证时。它应该被执行并且应该将我带到 fb 登录页面,但没有这样做。即使它显示 Not Found 也不会抛出任何类型的错误。这是我的代码示例:
app.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
social.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
,并且运行良好。
我能看到的第一件事是您没有正确地将用户序列化进出会话。尝试将 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);
});
天哪,经过这么多的查找,得到了答案。
问题出在依赖项上。
koa-passport 将使用@next 标签安装,即 npm install koa-passport@next
而不是 npm install koa-passport@latest
我正在尝试使用护照在 KOA2 中进行社交登录。当我尝试在 passport.authenticate() 的帮助下对用户进行身份验证时。它应该被执行并且应该将我带到 fb 登录页面,但没有这样做。即使它显示 Not Found 也不会抛出任何类型的错误。这是我的代码示例:
app.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
social.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
,并且运行良好。
我能看到的第一件事是您没有正确地将用户序列化进出会话。尝试将 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);
});
天哪,经过这么多的查找,得到了答案。
问题出在依赖项上。
koa-passport 将使用@next 标签安装,即 npm install koa-passport@next
而不是 npm install koa-passport@latest