[英]Cookie-based authentication works on desktop browsers but not on mobile ones
我在后端使用 express.js 和 Sequelize,我的身份验证路径如下所示:
exports.signin = (req, res) => {
Admin.findOne({
where: {
username: req.body.username
}
})
.then(admin => {
if (!admin) {
return res.status(404).send({
ERR: USER_NOT_FOUND
});
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
admin.password
);
if (!passwordIsValid) {
return res.status(401).send({
ERR: WRONG_PASSWORD
});
}
const tokenBody = {
id: admin.id,
isMaster: (admin.username == "Master")
};
var token = jwt.sign(tokenBody, process.env.JWT_SECRET, {
expiresIn: tokenExpirationTime
});
res.cookie('auth_token', token, {
// 'tokenExpirationTime' is in seconds (as required for JWT), but maxAge
// expects milliseconds, so it must be multiplied by 1000:
maxAge: tokenExpirationTime * 1000,
httpOnly: true,
secure: true
});
res.status(200).send({ success: true });
})
.catch(err => {
console.error(err);
res.status(500).send({
ERR: INTERNAL_SERVER_ERROR
});
});
};
我在前端使用 Ejs,我的登录代码是:
const signInUrl = '/api/auth/signin';
let form = document.getElementById('login');
form.onsubmit = async (e) => {
e.preventDefault();
let data = new FormData(form);
data = {
username: data.get('username'),
password: data.get('password')
};
axios.defaults.withCredentials = true
axios.post(signInUrl, data, { withCredentials: true })
.then(response => {
// Redirect to the home page:
if (response.data.success)
window.location.replace('/');
else // console.log(response.data);
informError(0);
})
.catch(error => {
console.error(error);
if (error.response) {
if (error.response.data && error.response.data.ERR)
informError(error.response.data.ERR);
else
informError(0);
} else {
informError(1);
}
});
}
现在的问题是该系统在桌面浏览器上完全正常(我已经使用它一个多月了,它通过了各种测试)但在移动浏览器上却没有!
在移动设备上,我登录并成功将我重定向到主页,但随后我仍在使用登录按钮,表明我未登录。此外,我无法访问任何受保护的路由,收到一个“需要登录”错误!
任何帮助将不胜感激!
所以对于那些有同样问题的人,对我来说,当我尝试使用如下 URL 从我的手机访问服务器(在我的笔记本电脑“localhost:3000”上)时出现问题: http://192.168.0.107:3000
: http://192.168.0.107:3000
:3000 . 我发现问题与被保护的 cookie ( secure: true
) 相关,移动浏览器没有使用它,因为我使用的是 http 而不是 https,而是桌面浏览器正常使用。 所以我想在 https 协议的域上部署应用程序将解决这个问题。 但出于测试目的,只需删除secure: true
部分,它就会正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.