提问人:Michael 提问时间:11/9/2023 更新时间:11/9/2023 访问量:8
未发送 Cookie 护照 .js 节点 .js
cookie not being sent passport.js node.js
问:
所以我面临一个问题,我正在为我的网站做一个后端,其中后端和前端位于不同的端口上,这意味着我们有 CSR。我使用passport.js进行身份验证,并将会话保存在mysql存储中。但是,当我检查浏览器时,显然没有发送cookie。 我用代码签入了代码,但是我只得到了未定义,可能是什么问题?console.log("Set-Cookie Header:", res.get('Set-Cookie'));
loginRoute.js
const express = require('express');
const passport = require('./passport-config');
const router = express.Router();
// Define the login route for local authentication
router.post('/', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.log("An error occurred:", err);
return res.status(500).json({ message: 'An error occurred' });
}
if (!user) {
console.log("Authentication failed");
return res.status(401).json({ message: 'Authentication failed' });
}
req.login(user, (loginErr) => {
if (loginErr) {
console.log("Error serializing user:", loginErr);
return res.status(500).json({ message: 'An error occurred during login' });
}
console.log("Set-Cookie Header:", res.get('Set-Cookie'));
return res.status(200).json({ message: 'Authentication successful', email: user.email });
});
})(req, res, next);
});
护照配置.js
// Import necessary modules and dependencies
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const { addUser, isUserUnique, findUserByUsername, findUserById, findUserByEmail, addOauth2User } = require('../db/database');
// Configure a LocalStrategy for username and password authentication
passport.use(new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password',
},
async (username, password, done) => {
try {
const [user] = await findUserByUsername(username);
if (!user) {
return done(null, false); // User not found
}
if (!bcrypt.compare(password, user.password)) {
return done(null, false); // Password does not match
}
return done(null, user); // Authentication successful
} catch (error) {
return done(error); // Error during authentication
}
}
));
// Serialize and deserialize user data for session management
passport.serializeUser((user, done) => {
console.log("serializing the user", user.id)
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await findUserById(id);
console.log(user)
console.log("[popsopfsfefszfs")
return done(null, user);
} catch (error) {
return done(error);
}
});
主文件
app.use(session({
secret: process.env.SECRET,
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24, // 1 day
sameSite: 'None',
httpOnly: true,
secure: false // Change this to false if testing over HTTP
},
store: sessionStore
}));
// Initialize Passport for user authentication
app.use(passport.initialize())
app.use(passport.session())
最后,为会话设置的MySQL
const mysql = require('mysql2/promise');
const session = require('express-session');
const MySQLStore = require('express-mysql-session')(session);
require('dotenv').config();
// Create a MySQL connection pool
const pool = mysql.createPool({
host: process.env.HOST,
user: "root",
password: process.env.PASSWORD,
database: "uniHub",
connectionLimit: 10,
});
// Create a session store using MySQL for Express
const sessionStore = new MySQLStore({ createDatabaseTable: true }, pool);
我尝试将存储从MySQL更改为内存存储。我尝试了很多次更改登录路由,但似乎没有任何帮助。也许从数据库中提取会话数据有问题?我还尝试将sameSite: 'None'更改为其他值,并且没有任何帮助。 cors 还设置了 app.use(cors({ 起源: 'http://localhost:5173', 凭据:true、 }));
答: 暂无答案
评论