【问题标题】:How to add header to axios on nuxt project for hmac authentication如何在 nuxt 项目上将标头添加到 axios 以进行 hmac 身份验证
【发布时间】:2021-12-05 00:11:16
【问题描述】:

有一个远程 api,它需要 hmac sha256 密钥,该密钥由每个请求的密钥和时间戳生成。

不应在 Nuxt 项目的客户端代码中看到此 hmac 标头生成。并且请求必须在服务器端使用 hmac 标头进行。例如,我将向 api 发送登录帖子请求。我将发送密码、电子邮件和 hmac 密钥作为标题。但是必须为客户端隐藏此标头生成代码。并且发布请求应该在服务器端完成。不是客户端。

Api 需要这个 hmac 密钥头。要生成 hmac 密钥,您需要 api 提供者提供给我们的密钥。您可以看到 hmac 生成如何在 this link 上工作。我们将放置一些数据和时间戳。所以 api 解密密钥并检查时间戳。如果时间戳增量超过 20 秒,则请求不会被 api 接受。

如何将此标头添加到 axios 仅用于 axios 请求的服务器端调用,并且不应在客户端代码上看到此生成脚本?

X-HMAC-TOKEN: 'hmac sha256 key generated with timestamp and secret key. and this generation script should not seen on client code'

Here is an example hmac authentication example on api side.

【问题讨论】:

  • 这个令牌什么时候使用?做什么的?因为只有特定的地方可以使用私有变量:本质上只有 SSR + 在构建期间。
  • 每个请求在 api 端使用生成的 hmac 密钥有 20 秒的生命周期。这是出于 api 方面的安全原因。它是 hmac sha256 加密密钥。所以在 Nuxt 项目中,它应该在某处生成并作为标头添加到所有 axios 请求中,但仅适用于服务器端请求
  • 您的应用何时会使用这些服务器端请求?另外,您的 Nuxt 应用程序的设置是什么?
  • 例如从 api 请求私有数据。所以 api 需要这个 hmac 密钥。并且生成 hmac 密钥需要 api 提供者给我们的密钥。您可以在此链接上查看 hmac 生成是如何工作的。我们将放置一些数据和时间戳。所以 api 解密密钥并检查时间戳。如果时间戳增量超过 20 秒,则不会通过 api 接受请求。 devglan.com/online-tools/hmac-sha256-online
  • @kissu 我还没有应用程序。如果我不能解决这个问题,我不会在项目中使用 Nuxt

标签: vue.js axios nuxt.js


【解决方案1】:

似乎唯一的解决方案看起来像使用服务器中间件并且可能表达。

这是一个在github 上共享的示例代码。我只是想在这里为所有有这个问题的人分享代码

首先你应该在 /api 文件夹 /api/remote-api.js 中创建服务器中间件

// remote-api.js
const path = require('path');
const bodyParser = require('body-parser');
const app = require('express')();
const axios = require('axios');
const cors = require('cors');

require('dotenv').config({ path: path.resolve(process.cwd(), '.env.server') });

app.use(cors());
app.use(bodyParser.json());

app.get('/remote-api', (req, res) => {
  req.body.sha256_key = "whatever you specify"
  req.body.timestamp ="whatever you specify"
  axios
    .get(process.env.REMOTE_API_URL}, { 
      params: {
        term: req.query.q
      }
    })
    .then((response) => {
      res.json({ data: response.data });
    })
    .catch((error) => {
      res.json(error);
    });
});

module.exports = app;

那么你应该在 nuxt.config.js 中指定这个文件

serverMiddleware: ['~/api/remote-api'],

【讨论】:

  • 是的,但这仅适用于服务器调用。应用完成后,您将开始使用客户端导航,并且您的通话将公开可见(因为在客户端上)。
猜你喜欢
  • 2020-03-24
  • 2014-06-02
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多