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

标签 javascript node.js express authentication jwt

我想使用 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/

相关文章:

node.js - 从 JSON 创建 TS 类实例时是否可以处理未知属性?

javascript - 如何使用 MongoDB + Node.js API 连接两个表?

javascript - 错误对象, native 和自定义,如何区分?

session - 快速 session key 属性

javascript - 有没有一种简单/快速的方法可以将 "data-"属性映射到大小写混合的属性名称?

javascript - 当我需要为每个元素使用不同的 id 时,如何通过仅加载一次来多次使用相同的图像

javascript - 遍历在nodeJs中具有嵌套对象的对象

node.js - 如何使用 Express 将 powershell 命令结果推送到 NodeJs 中的 json 响应?

javascript - 从 GeocoderResult 获取 formatted_address 组件

javascript - 更改 'onchange' 的选择