gpt4 book ai didi

javascript - 使用 token 在后端和前端识别用户进行身份验证

转载 作者:行者123 更新时间:2023-11-30 14:07:46 25 4
gpt4 key购买 nike

我想使用 Json Web Tokens 创建一个简单的 Express API。当用户尝试登录时,我执行此

exports.signIn = async (req, res, next) => {
const { username, password } = req.body;

// get user from database
const userQueryResult = await userQueries.getUserByName([username]);

// return if database errors occured
if (userQueryResult.err) {
res.status(500).json({
message: userQueryResult.err.message
});
}

const users = userQueryResult.result;
const user = users[0];

// no user found
if (!user) {
res.status(401).json({
message: 'Auth failed'
});
}

try {
// validate the password
const passwordMatch = bcrypt.compareSync(password, user.passwordHash);

// wrong credentials
if (!passwordMatch) {
res.status(401).json({
message: 'Auth failed'
});
}

const token = jwt.sign({
user.id
}, tokenSecret, {
tokenExpiration
});

res.status(200).json({
message: 'Auth succeeded',
token
});
} catch (err) {
res.status(401).json({
message: 'Auth failed'
});
}
};

生成一个新 token 并发送给客户端。我是否也必须将用户对象发送给客户端?因为目前我只检查用户是否已通过身份验证,而不是检查哪个用户。

对于 protected 路由,我使用中间件函数检查用户是否已通过身份验证

module.exports = (req, res, next) => {
try {
const rawToken = req.headers.authorization; // bearer <token>
const token = rawToken.split(' ')[1]; // extract the token
req.userData = jwt.verify(token, tokenSecret); // verify this token
next();
} catch (error) {
res.status(401).json({
message: 'Auth failed'
});
}
}

那么您是否也将用户 ID 发送给客户端?是不是和token一起存储到本地浏览器存储,移除token的时候删除?

也许我弄错了,但目前我只知道如何检查某人是否已通过身份验证,但不知道是哪一个。客户端需要知道哪个用户当前已登录。

最佳答案

A new token gets generated and is sent to the client. Do I have to send the user object to the client too? Because currently I'm only checking if a user is authenticated but not which one.

从技术上讲,您也可以发送用户对象(和任何其他信息),但通常您想要发回的只是 jwt token ,因为它包含您在客户端需要的所有信息(有效负载)。

So would you send the user id to the client too?

与之前的答案相同,如果您需要客户端的用户 ID,则将其包含在 jwt 有效负载中。

Do you store it to the local browser storage with the token and delete it when removing the token?

如果您需要它作为永久性的东西(页面重新加载),是的,将 jwt token 或任何其他与此相关的东西保存到本地存储中。

Maybe I got it wrong but currently I only know how to check if someone is authenticated but not which one. The client needs to know which user is currently signed in.

您正在寻找的是您在服务器端检查的用户授权(而不是身份验证)。

关于javascript - 使用 token 在后端和前端识别用户进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086106/

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