我试图找出为什么这个简单的代码不起作用,但我无法弄清楚。问题是在成功登录后,未填充req.user并且req.isAuthenticated返回false。
我知道类似的问题被多次询问,但我没有找到任何解决方案。 感谢。
import * as path from 'path'
import * as express from 'express'
import * as session from 'express-session'
import * as bodyParser from 'body-parser'
import * as passport from 'passport'
import { BasicStrategy, DigestStrategy } from 'passport-http'
import checkAuthentication from './db'
const app: express.Application = express()
// Configure session store (memory)
app.use(session({
store: undefined,
secret: 'stackoverflow_please_help!',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true
}
}))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(passport.initialize())
app.use(passport.session())
// This should fill the req.user
passport.serializeUser((user: string, done: express.NextFunction): express.NextFunction => {
console.log(`[serializeUser] user:`, user)
return done(null, user)
})
// Should retrive serialized data (user)
passport.deserializeUser((user: string, done: express.NextFunction): express.NextFunction => {
console.log(`[deserializeUser] user:`, user)
return done(null, user)
})
// Check if username and password from user are correct
passport.use(
new BasicStrategy(async (username: string, password: string, done: express.NextFunction ): express.NextFunction => {
let userValidated
try {
userValidated = await checkAuthentication(username, password)
} catch {
console.error(`Something wrong calling db.`)
return done(`Something wrong calling db.`)
}
if (userValidated) {
console.log(`[BasicStrategy] "${username}" login succesfull`)
return done(null, username)
} else {
console.log(`[BasicStrategy] "${username}" login failed`)
return done(null, false)
}
}))
const routePages: express.Router = express.Router()
// Authenticate user with BasicStrategy, set session, call req.login, redirect if success or failure
routePages.post('/auth',
passport.authenticate('basic',
{
successRedirect: '/secure/profile',
failureRedirect: '/login.html'
})
)
// Protected page
routePages.get('/profile', isLoggedIn, (req: express.Request, res: express.response) => {
res.set('Content-Type', 'text/html');
res.status(200).send('<h1>Works!</h1>')
})
// Add routes path
const staticFilePath: string = path.join(__dirname, '..', 'www')
app.use('/', express.static(staticFilePath))
app.use('/secure', routePages)
// route middleware to make sure a user is logged in
function isLoggedIn(req: express.Request, res: express.response, next: express.NextFunction) {
console.log(`[isLoggedIn] authenticated? :`, req.isAuthenticated())
console.log(`[isLoggedIn] req.sessionID:`, req.sessionID)
console.log(`[isLoggedIn] req.user:`, req.user)
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if not authenticated, redirect them to the home page
return res.redirect('/login.html');
}
const listeningPort = 3333
app.listen(listeningPort)
console.log(`Listening to ${listeningPort}`)
我得到的console.log是:
Listening to 3333
[BasicStrategy] "admin" login succesfull
[serializeUser] user: admin
[isLoggedIn] authenticated? : false
[isLoggedIn] req.sessionID: XtPFNEMLbAKxWRRXHwxHKnhTamloicaj
[isLoggedIn] req.user: undefined
软件版本:
"dependencies": {
"@types/node": "^7.0.60",
"body-parser": "^1.18.2",
"express": "^4.16.3",
"express-session": "^1.15.6",
"passport": "^0.4.0",
"passport-http": "^0.3.0"
}
答案 0 :(得分:1)
我发现了问题。我使用安全cookie 但连接不在SSL中。 我很抱歉