【问题标题】:How do i store jsonwebtoken on cookie for front-end so client can send back the token for auth我如何将 jsonwebtoken 存储在前端的 cookie 上,以便客户端可以发回令牌以进行身份​​验证
【发布时间】:2020-08-01 11:25:27
【问题描述】:

我已经为此苦苦挣扎了大约 6 天... 一切都运行良好,例如授权,但我遇到的一个问题是进行身份验证。

在我的用户模型(用于创建数据库架构)上,我确实有办法为登录用户或注册用户生成令牌。

userSchema.methods.generateAuthToken = function(){
    const token = jwt.sign({ _id: this._id }, config.get('jwtPrivateKey'));
    return token;
}

所以当用户发布到 /login 时,服务器会用一个令牌响应:

router.post('/', async (req, res) =>{
    // Here i'm validating data and then if everything is right the code under will run.
    console.log('logged in as: ' + user.username);
    // Here i'm using the function to generateAuthToken().
    const token = user.generateAuthToken();
    console.log("Token from server: " + token);
    // now here is my main problem i would like to use cookies to store it for an hour or so.
    // then client can send it back to server for protected route.
    res.status(200).send(token);
});

我已经为 auth 创建了一个中间件功能(如果您正在通过受保护的路线检查令牌)

module.exports = function (req, res, next){
    // instead of using headers i would like to check for the cookie value if it's the token,
    // pass the user in, else Access denied.
    // I have no idea how to use cookie parser with middleware functions.
    const token = req.header('x-auth-token');
    if(!token) return res.status(401).send('Access denied. Sign in or register.');

    try{
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
        req.user = decoded;
        next();
    }
    catch(err){
        res.status(400).send('Invalid Token!');
    }
}

这里我使用的是 auth 中间件功能:

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');

// but it's actually not passing the user in since i haven't done it with cookies.
router.get('/', auth, (req, res) =>{
    res.render('index', {});
});

我知道我可以使用 localStorage 来做到这一点,但这是一种糟糕的做法,最好将其存储在 cookie 上,这样就没有人可以破解了。 有什么好的方法可以解决这个问题吗?我有点迷失了,失去了回到 sessionID 的希望(我不想这样做:()。

【问题讨论】:

    标签: javascript node.js express authentication jwt


    【解决方案1】:

    在前端请求后,您需要在 浏览器 上获取响应(令牌)和保存,例如:

    fetch('http://your-api-host/login', {
        method: 'POST',
        body: {
          username: "user1",
          password: "passworduser" 
        }
     })
    .then((res) => res.text((res)))
    .then((token) => {
       document.cookie = `AUTH_API=${token}`;  <-- this save the cookie
    })
    

    将此值保存在前端后,您需要在所有请求中发送此信息,这是常见的在您的 HEADER 上发送此值(您如何制作),要保存在标头上,您需要从令牌中读取值并放入标头,像这样:

    const headersTemp = document.cookie.split(';');   // <-- this get all cookies saves and splits them in the array.
    
    const finalHeaders = {};
    headersTemp.forEach((header) => {   // <-- looping on all cookies
      const headerTemp = header.split('='); // <-- split each cookie to get key and value
      finalHeaders[headerTemp[0].trim()] = headerTemp[1].trim()   // <-- save on object to access using keys.
    })
    

    现在您可以使用密钥访问所有 cookie(与之前使用的相同),我使用密钥 AUTH_API 来保存我的 cookie,让我们使用 fetch api 发送请求:

    fetch('http://your-api-host/route-protected', {
        method: 'POST',
        headers: {
          'x-auth-token': finalHeaders['AUTH_API']
        },
      })
    

    如果您使用 React 或任何 SPA 框架等库创建应用程序,您可能会使用 Axios 之类的工具,我建议您使用库This,使用 cookie 更容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 2019-03-13
      • 1970-01-01
      • 2017-08-15
      • 2020-12-03
      • 2021-05-18
      • 2011-04-11
      相关资源
      最近更新 更多