保护 NodeJS API
创始人
2024-11-23 21:00:50
0

保护 Node.js API 的方法有很多种,下面给出两种常见的解决方案以及相应的代码示例:

  1. 使用 API 密钥进行身份验证:

    • 在客户端请求 API 时,需要提供有效的 API 密钥。
    • 在服务器端,验证客户端提供的 API 密钥是否有效。

    代码示例:

    // 客户端请求 API
    const apiKey = 'your-api-key';
    const url = 'http://example.com/api';
    const headers = { 'Authorization': `Bearer ${apiKey}` };
    
    fetch(url, { headers })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
    
    // 服务器端验证 API 密钥
    const express = require('express');
    const app = express();
    
    const validApiKeys = ['your-api-key'];
    
    app.get('/api', (req, res) => {
      const apiKey = req.headers.authorization.replace('Bearer ', '');
      if (validApiKeys.includes(apiKey)) {
        // 执行 API 逻辑
        res.json({ message: 'API request successful' });
      } else {
        res.status(401).json({ error: 'Invalid API key' });
      }
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    
  2. 使用 JSON Web Tokens (JWT) 进行身份验证:

    • 客户端通过提供有效的 JWT 进行身份验证。
    • 服务器端验证客户端提供的 JWT 是否有效,并从中提取用户身份信息。

    代码示例:

    // 客户端请求 API
    const jwt = 'your-jwt';
    const url = 'http://example.com/api';
    const headers = { 'Authorization': `Bearer ${jwt}` };
    
    fetch(url, { headers })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
    
    // 服务器端验证 JWT
    const express = require('express');
    const app = express();
    const jwt = require('jsonwebtoken');
    
    const secretKey = 'your-secret-key';
    
    app.get('/api', (req, res) => {
      const token = req.headers.authorization.replace('Bearer ', '');
      try {
        const decoded = jwt.verify(token, secretKey);
        // 执行 API 逻辑
        res.json({ message: 'API request successful', user: decoded.user });
      } catch (error) {
        res.status(401).json({ error: 'Invalid JWT' });
      }
    });
    
    app.listen(3000, () => {
      console.log('Server is running on port 3000');
    });
    

请注意,以上代码示例仅用于演示目的,实际应用中可能需要根据具体业务需求进行适当的修改和改进。

相关内容

热门资讯

透视系统!微信雀神麻将软挂神器... 广东雀神智能插件安装使用版本解析‌,透视系统!微信雀神麻将软挂神器(辅助挂)原来真的有挂(揭秘有挂)...
来一盘!欢乐卡五星小程序辅助(... 来一盘!欢乐卡五星小程序辅助(辅助挂)其实是真的有挂(揭秘有挂)-哔哩哔哩欢乐卡五星小程序辅助平台为...
透视能赢!aapoker软件有... 透视能赢!aapoker软件有猫腻吗!果真真的有挂((2021已更新))(哔哩哔哩)1、让任何用户在...
4分钟实锤!wpk发牌算法(透... 4分钟实锤!wpk发牌算法(透视)透视辅助((2021已更新))(哔哩哔哩),亲,有的,ai轻松简单...
2分钟了解!开心联盟怎么开挂(... 1、2分钟了解!开心联盟怎么开挂(辅助挂)竟然是真的有挂(今日头条)-哔哩哔哩。2、开心联盟怎么开挂...
科普攻略!广东雀神智能插件安装... 广东雀神辅助器最新版版本稳定性对比与推荐‌:科普攻略!广东雀神智能插件安装如何使用(辅助挂)果真是真...
每日必看推荐!we poke有... 每日必看推荐!we poke有挂吗!的确是真的有挂((2024已更新))(哔哩哔哩);简单的灵活控制...
8分钟攻略!线上德州aapok... 8分钟攻略!线上德州aapoker透明挂(透视)透视辅助((2024已更新))(哔哩哔哩)1、线上德...
玩家必看教程!老友麻将插件(辅... 玩家必看教程!老友麻将插件(辅助挂)原来是真的有挂(真是有挂)-哔哩哔哩;实战中需综合运用上述技巧,...
信息共享!广东雀神麻雀胜率会提... 信息共享!广东雀神麻雀胜率会提升(辅助挂)原来是真的有挂(有挂解密)-哔哩哔哩;是一款可以让一直输的...