我在node.js
中使用以下代码对使用Google的用户进行身份验证。我使用passport-google-oauth
模块。虽然我相当确定代码是正确的,但应用程序根本不会将我重定向到Google登录页面。请帮帮我。
以下是代码(使用express.js 4.9.0
):
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var session = require('express-session');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new GoogleStrategy({
clientID: MY CLIENT ID,
clientSecret: MY CLIENT SECRET,
callbackURL: "http://127.0.0.1:1337/auth/google/callback"
},
function (accessToken, refreshToken, profile, done) {
process.nextTick(function () {
return done(null, profile);
});
}
));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// required for passport
app.use(session({ secret: 'victoriassecret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.get('/', function (req, res) {
//res.render('index', { title: 'Collaborative' });
res.sendFile(path.join(__dirname, '../public', 'login.html'));
});
app.get('/auth/google',passport.authenticate('google', {
scope: ['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/userinfo.email']
}),
function (req, res) {
// The request will be redirected to Google for authentication, so this
// function will not be called.
});
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),
function (req, res) {
res.redirect('/profile');
});
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(1337);
module.exports = app;