简体   繁体   English

护照 - 无法读取属性“isAuthenticated”

[英]Passport - Cannot read property 'isAuthenticated'

I am trying to fix the following error:我正在尝试修复以下错误:

/home/ubuntu/workspace/src/util/utils.js:2
  if (req.isAuthenticated()) {
          ^

TypeError: Cannot read property 'isAuthenticated' of undefined
    at Object.isLogged (/home/ubuntu/workspace/src/util/utils.js:2:11)
    at Object.<anonymous> (/home/ubuntu/workspace/src/routes/index.js:6:23)

I am using passport the following in my app:我在我的应用程序中使用以下护照:

require('dotenv').config()
const express = require('express')
//...
const session = require('express-session')
const passport = require('passport')
// configure passport
require('./config/passport')(passport)
const auth = require('./routes/auth')
const index = require('./routes/index')

const app = express()

// ...
app.use(
  session({
    secret: 'super-mega-hyper-secret',
    resave: false,
    saveUninitialized: true,
  })
)
app.use(passport.initialize())
app.use(passport.session())

app.use((req, res, next) => {
  res.locals.currentUser = req.user
  next()
})

// routes
app.use('/', auth)
app.use('/', index)

app.listen(port, host, () => {
  console.log(`Listening on ${host}:${port}`)
})

module.exports = app

My passport.js file looks like the following:我的passport.js 文件如下所示:

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const service = require('../service/auth')

module.exports = () => {
passport-serialize-deserialize
  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser(async function(id, done) {
    const user = await service.findById(id)
    done(null, user)
  })

  passport.use('local', new LocalStrategy({
    usernameField: 'username',
  }, async(username, password, done) => {
    const user = await service.signin(username, password)
    done(null, user)
  }))
}

When my / gets called I am using the isLogged() function to control if a login is required:当我的/被调用时,我使用isLogged()函数来控制是否需要登录:

const express = require('express')

const router = express.Router()
const utils = require('../util/utils')

router.get('/', utils.isLogged(), (req, res) => {
  res.render('dashboard')
})

module.exports = router

The definition of the function can be found in my utils.js file, where the error log above is pointing:该函数的定义可以在我的utils.js文件中找到,上面的错误日志指向:

function isLogged(req, res, next) {
  if (req.isAuthenticated()) {
    next()
  } else {
    res.redirect('/')
  }
}

module.exports = {
  isLogged,
}

The full code flow can be found in the following repo: passport example完整的代码流可以在以下 repo 中找到: passport example

Any suggestions what I am doing wrong?`有什么建议我做错了吗?`

I appreciate your replies!我感谢您的回复!

When you run this code:当您运行此代码时:

router.get('/', utils.isLogged(), (req, res) => {
  res.render('dashboard')
});

What happens is that utils.isLogged() is being executed, the the result of this execution is registered as a middleware.发生的情况是utils.isLogged()正在执行,此执行的结果被注册为中间件。
Since you try to execute it without any parameters passed, res is passed as undefined and you get your error.由于您尝试在不传递任何参数的情况下执行它,因此res被传递为 undefined 并且您会收到错误消息。

Now, what you really want to do is pass the function itself, not it's execution, so when express will call it (during request processing), it will pass the parameters to it.现在,你真正想做的是传递函数本身,而不是它的执行,所以当 express 调用它时(在请求处理期间),它会将参数传递给它。 So your code should look like this:所以你的代码应该是这样的:

router.get('/', utils.isLogged, (req, res) => {
  res.render('dashboard')
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Passport.js:无法读取未定义的属性“用户名”(节点) - Passport.js: Cannot read property 'username' of undefined (Node) 无法使用护照读取 nodejs 中未定义的属性“名称” - Cannot read property 'name' of undefined in nodejs using passport 护照OAuth承载者或已认证 - Passport OAuth Bearer OR isAuthenticated 无法在 Function.mapStateToProps 读取未定义的属性(读取“isAuthenticated”) - Cannot read properties of undefined (reading 'isAuthenticated') at Function.mapStateToProps 无法运行护照登录策略。 身份验证错误~类型错误:无法读取未定义的属性“身份验证” - Trouble running passport login Strategy. Authentication error~ TypeError: Cannot read property 'authenticate' of undefined TypeError:使用Passport.js时无法读取未定义的属性“ headersSent” - TypeError: Cannot read property 'headersSent' of undefined when using Passport.js Passport js中的isAuthenticated()始终返回false - isAuthenticated() in Passport js always return false 如何使用护照检查is组件上的isAuthenticated - How to check isAuthenticated on react component using passport isAuthenticated() 函数不起作用 node.js 护照 - isAuthenticated() function not working node.js passport 护照req.isAuthenticated()总是返回fasle - passport req.isAuthenticated() always returns fasle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM