【发布时间】:2021-11-11 21:45:46
【问题描述】:
我在后端使用 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);
}
});
}
现在的问题是系统在桌面浏览器上运行良好(我已经使用了一个多月了,它通过了各种测试),但在移动浏览器上却不行!
在移动设备上,我正在登录并成功将我重定向到主页,但是我仍在使用登录按钮,表明我没有登录。另外,我无法访问任何受保护的路线,收到“需要登录”错误!
任何帮助将不胜感激!
【问题讨论】:
标签: node.js express authentication cookies axios