gpt4 book ai didi

node.js - Express Passport.js 未在 session 中保留用户对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:39 25 4
gpt4 key购买 nike

我有一个在端口 3000 上运行的 Express 应用程序。前端在端口 80 上运行,因此这是一个 CORS 应用程序。用户存储在 SQL Server 数据库中。我使用 Passport 作为本地策略以及快速 session 中间件的身份验证方法。该应用程序是单页应用程序,发送到服务器的所有请求都是通过 ajax 完成的。用户在页面登录并发送凭据,如果身份验证成功,则 userID 以及用户名和 FullNmae 应保留到 session 中。

我对此有很多问题:主要是登录后,express 使用 Passport 将用户名和其他数据保存到新 session 中,并发回 html 片段以替换页面上的 body 标记。但是,为了测试用户对象是否持续存在,我调用/create-user 路由,它说用户对象不存在。此外,每个请求都会启动一个新 session (我检查日志并发现每次都会显示不同的 session ID)。不仅如此,有一次我能够在浏览器中看到 session cookie,但我再也看不到它了。我尝试返回到可以看到 cookie 的位置,但它仍然没有出现!

我已经绞尽脑汁好几个小时了,不明白为什么不调用 deserializeUser 也不明白为什么数据不持久。我哪里出错了?

注意:省略了一些明显的代码(app.listen()、require 语句等)

/* ------ CONFIGURATIONS ------ */
const app = express();
const mssqlConfig = JSON.parse(fs.readFileSync("mssql-config.json", "utf8"));
passport.use(new LocalStrategy(
function loginAuthentication(username, password, done) {
let connPool = new mssql.ConnectionPool(mssqlConfig);
connPool.connect(error => {
if (error) {console.log(error); return done(error);}
ps = new mssql.PreparedStatement(connPool);
ps.input('username', mssql.NVarChar(20));
ps.input('password', mssql.NVarChar(50));
ps.prepare('SELECT FullName, fldLoginName, fldEmployeeID, fldPassword FROM tblEmployees WHERE fldLoginName = @username AND fldPassword = @password;', error => {
if (error) {console.log(error); return done(error);}
ps.execute({username, password}, (error, result) => {
if (error) {console.log(error); return done(error);}
console.log(result);
if (result.recordset.length == 0) {
return done(null, false, {message: "There is no user with those credentials!"});
} else if (result.recordset[0].fldLoginName != username || result.recordset[0].fldPassword != password) {
return done(null, false, {message: "Username or password is incorrect!"})
} else {
return done(null, {
ID: result.recordset[0].fldEmployeeID,
username: result.recordset[0].fldLoginName,
fullName: result.recordset[0].FullName
});
}
ps.unprepare(error => console.log(error));
});
});
});
}
));
passport.serializeUser((user, done) => {
done(null, JSON.stringify(user));
})
passport.deserializeUser((user, done) => {
console.log(user);
done(null, JSON.parse(user));
});

/* ----- MIDDLEWARE ------ */
app.use(function allowCrossDomain(request, response, next) { // CORS
// intercept OPTIONS method
response.header('Access-Control-Allow-Credentials', true);
response.header('Access-Control-Allow-Origin', request.headers.origin);
response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
response.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
response.header('Access-Control-Max-Age', '60');
if ('OPTIONS' == request.method) {
response.sendStatus(200);
} else {
next();
}
});
app.use(bodyParser.json());
app.use(session({
secret:"long string of characters",
name:'officetools-extensions',
saveUninitialized:false,
resave:false,
cookie:{secure:false, httpOnly:true, maxAge:86400000, domain:"http://officetools-extensions"},
store: new MemoryStore({checkPeriod:86400000})
}));
app.use(passport.initialize());
app.use(function checkRestrictedURL(request, response, next){
console.log(request.url);
if (!request.url.match(/^\/login$/g)) {
console.log("passed");
passport.session()(request, response, next);
} else {
next();
}
});

/* ------ ROUTES ------ */
app.post('/login', bodyParser.urlencoded({extended:false}), (request, response, next) => {
passport.authenticate('local', {session:true}, (error, user, info) => {
if (error) { error.status = 500; return next(error); }
if (info) { let err = new Error(info.message); err.status = 400; return next(err);}
if (!user) { return response.status(401).send("User could not be logged in!"); }
console.log(request.sessionID);
console.log(user);
console.log(request.session);
request.logIn(user, function loginCallBack(error) {
if (error) { error.status = 500; return next(error);}
console.log("after login", request.session);
console.log(request.isAuthenticated());
return response.sendFile(path.join(__dirname + "/templates/barcodes.html"));
})
})(request, response, next);
});
app.get("/current-user", (request, response, next) => {
console.log(request.user, request.session);
console.log(request.sessionID);
console.log(request.isAuthenticated());
if (request.user) {
response.header("Content-Type", "application/json");
return response.send(request.user);
}
else { return response.status(401).send("There is no user currently logged in!"); }
});

最佳答案

我明白了。我只需删除 session 设置上的域属性即可。这样就成功了。

关于node.js - Express Passport.js 未在 session 中保留用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47703173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com