Passport身份验证不适用于具有快速路由器的特定路由

时间:2017-02-14 22:25:36

标签: node.js express passport.js express-session

我试图访问' testpage'路线。但是req.isAuthenticated()仅为此路由返回false。 (在我开始添加身份验证之前,这条路由就在那里)。 我可以访问登录页面并通过谷歌进行身份验证。然后我就可以访问'注册'或者' user_profile'路线没有问题。

登录后如果我尝试:

  

本地主机:8080 / testpage

服务器将我发送给" /"。但如果我尝试:

  

本地主机:8080 / testpage#

最后使用哈希符号,页面将被渲染。

// routes/users.js

var express = require('express');
var router = express.Router();

module.exports = function (passport) {
  router.get('/login', function (req, res) {
    res.render('login', { message: req.flash('loginMessage') });
  });

  router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));

  router.get('/auth/google/callback',
    passport.authenticate('google', {
      successRedirect: '/',
      failureRedirect: '/'
    }));

  router.get('/user_profile', isLoggedIn, function (req, res) {
    res.render('user_profile');
  });

  router.get('/signup', isLoggedIn, function (req, res) {
    res.render('signup');
  });

  router.get('/testpage', isLoggedIn, function (req, res) {
    res.render('testpage');
  });

  return router;

};

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated())
    return next();

  res.redirect('/');
}

为什么会发生这种情况?

*更新*

这是我的app.js

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 flash         = require('connect-flash');
var session       = require('express-session');
var db            = require('./mongoose');

var app = express();

require('./config/passport')(passport);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
    secret: 'secret123', 
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());


var users = require('./routes/users')(passport);

app.use('/', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;

2 个答案:

答案 0 :(得分:1)

这可能是由于护照所需的快速会话中间件。您可以按照以下顺序使用中间件来修复它。

var session = require('express-session')
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
   secret: 'yoursecret',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true },
   // you can store your sessions in mongo or in mysql or redis where ever     you want.
   store: new MongoStore({
      url: "mongourl,
      collection: 'sessions' // collection in mongo where sessions are to be saved
   })
}))
// Init passport 
app.use(passport.initialize());
// persistent login sessions 
app.use(passport.session());

有关详细信息,请参阅https://github.com/expressjs/session

另外我认为你没有配置谷歌策略。 尝试下面的事情

var GoogleStrategy = require('passport-google-oauth').OAuthStrategy;

// Use the GoogleStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a token, tokenSecret, and Google profile), and
//   invoke a callback with a user object.

passport.use(new GoogleStrategy({
    consumerKey: GOOGLE_CONSUMER_KEY,
    consumerSecret: GOOGLE_CONSUMER_SECRET,
    callbackURL: "http://www.example.com/auth/google/callback"
  },
  function(token, tokenSecret, profile, done) {
      User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
  });
 }

));

答案 1 :(得分:0)

最后一天后,我才意识到,当我在url栏中输入localhost:8000 / testpage时,它已被更改为www.localhost:8000 / testpage。并且auth dos不适用于www *。另一件事是谷歌浏览器试图预测你将键入的URL,这可能会导致这种类型的错误,并且它在调试时很烦人。所以我在chrome的设置中取消选中这个选项,阻止预测。

unchecked google chrome's settings