我已经创建了一个应用程序,我想为未经身份验证的用户提供一些功能。
到目前为止,我有一个工作正常的React前端,一个Express后端和PassportJs处理用户身份验证/授权。
到目前为止,只有登录的用户才能获得具有其会话存储ID的Cookie。
我将会话配置更改为包括saveUninitialized
到true
,现在每个访问该网站的客户端都获得了cookie集,并且我可以按预期提供功能。
问题出在前端存储库中向后端发出的某些请求,这些请求存储了“幽灵”会话。意思是说,弹出的会话不是由连接到后端的客户端设置的,因此我查看了对sessionID的每个请求,并且对于客户端的请求,会话ID保持不变/客户端的cookie也相同值。
例如,我的createLobby
路由会在正常的客户端会话之外生成一个“幽灵”会话,而我的deleteLobby
路由会按预期工作。
我不确定“幽灵”会话来自何处/正在发出请求以便创建它们。
app.use(
session({
name: 'SESS_ID',
cookie: {
httpOnly: true,
secure: app.get('env') === 'development' ? false : true,
maxAge: 1000 * 60 * 60 * 24,
},
secret: keys.session.secret,
store,
resave: false,
saveUninitialized: true,
})
);
import React, { useState, useRef, useEffect } from 'react';
import { BACKEND_URL } from 'GConfig';
import NewLobbies from './components/newLobby';
const Play = () => {
const [creatingLobby, setCreatingLobby] = useState(0);
const lobbyNameRef = useRef();
const lobbyPasswordRef = useRef();
useEffect(() => {
const createLobby = async () => {
const [error, lobbyId] = await (
await fetch(`${BACKEND_URL}/play/createLobby`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
lobbyName: lobbyNameRef.current.value,
lobbyPassword: lobbyPasswordRef.current.value,
}),
})
).json();
if (error) {
console.error(new Error(error));
return;
}
console.log(lobbyId)
// TODO : JOIN LOBBY WITH LOBBY ID
};
if (creatingLobby > 0) {
createLobby();
setCreatingLobby(0);
}
}, [creatingLobby]);
return (
<>
<NewLobbies />
<label htmlFor='lobbyName'>
Create Lobby with Name :
<input
ref={lobbyNameRef}
type='text'
name='lobbyName'
placeholder='Create a lobby with this name ...'
required
/>
</label>
<label htmlFor='lobbyPassword'>
Lobby Password :
<input
ref={lobbyPasswordRef}
type='password'
name='lobbyPassword'
placeholder="Leave this empty if you don't want your lobby to be open to everyone"
/>
</label>
<button type='button' onClick={() => setCreatingLobby(s => s + 1)}>
Create Lobby
</button>
</>
);
};
export default Play;
// Working route
router.post('/deleteLobby/:id', async (req, res) => {
if (!req.params.id) {
return res.json({ error: 'No ID on request' });
}
const user = req.user ? req.user.id : req.session.id;
try {
const result = await Lobby.findById(req.params.id);
if (result.owner === user) {
await Lobby.findByIdAndDelete(req.params.id);
return res.json({
success: `Lobby with ID : ${req.params.id} has been successfully removed`,
});
}
} catch (e) {
return res.json({
error: [`No Lobby with ID found : ${req.params.id}`, e.message],
});
}
});
// Not working route
router.post('/createLobby', async (req, res) => {
// validation
console.log(req);
res.send(await createLobby(req));
});