· Nacho Coll · Guides  · 14 分钟阅读

IPFS 上传令牌:无需暴露 API 密钥即可安全进行客户端上传

了解签名上传令牌如何让您从浏览器和移动应用安全上传到 IPFS,而无需暴露您的 API 密钥。

了解签名上传令牌如何让您从浏览器和移动应用安全上传到 IPFS,而无需暴露您的 API 密钥。

构建现代 Web 应用程序时,通常需要直接从用户的浏览器上传文件到云存储。然而,当涉及 IPFS 上传安全时,开发者面临一个棘手的难题:如何在不暴露宝贵 API 密钥的情况下允许客户端上传?

大多数 IPFS 固定服务迫使您做出不舒服的选择:要么在服务器端处理所有上传(造成瓶颈和复杂性),要么在客户端代码中嵌入 API 密钥(这是一个安全噩梦)。IPFS.NINJA 通过一个其他固定服务都没有的独特功能解决了这个问题:签名上传令牌

IPFS Ninja

传统 IPFS API 密钥的问题

当构建需要上传到 IPFS 的客户端应用程序时,开发者通常会遇到几个安全挑战:

API 密钥暴露风险

将 API 密钥直接嵌入浏览器 JavaScript 意味着任何人都可以查看您的源代码并提取您的凭据。这可能导致:

  • 未经授权的上传消耗您的存储配额
  • 您的固定服务账户可能被滥用
  • 在企业环境中违反安全合规要求

服务器端瓶颈

另一种方案——通过后端路由所有上传——会产生几个问题:

  • 服务器带宽成本增加
  • 用户延迟更高
  • 基础设施要求更复杂
  • 潜在的单点故障

移动应用安全

移动应用程序面临类似的挑战,存储在应用包中的 API 密钥可以通过逆向工程被提取。

IPFS 上传令牌介绍

IPFS.NINJA 的签名上传令牌提供了安全的折中方案。以下是其工作原理:

  1. 服务器生成令牌:您的后端使用 API 密钥创建一个限时签名令牌
  2. 客户端接收令牌:令牌安全地传输到您的前端应用程序
  3. 直接上传:客户端使用签名令牌直接上传到 IPFS.NINJA
  4. 自动过期:令牌在设定的时间后过期,限制暴露窗口

这种方法将服务器端身份验证的安全性与直接客户端上传的性能优势相结合。

理解上传令牌安全性

签名上传令牌使用加密签名来确保真实性,而无需暴露您的主 API 密钥。每个令牌包含:

  • 过期时间戳:在指定时间后自动失效
  • 使用限制:可选的文件数量或总大小限制
  • 加密签名:防止篡改或伪造
  • 发行者验证:链接回您的已认证账户

与 API 密钥不同,上传令牌被设计为可以安全地嵌入客户端代码中。即使被提取,它们提供的访问权限也是有限的,并且会自动过期。

后端实现:Express.js 示例

让我们构建一个完整的示例,展示如何实现安全的客户端 IPFS 上传。首先,这是生成上传令牌的 Express.js 后端:

// server.js
const express = require('express');
const cors = require('cors');
const app = express();

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

// Your IPFS.NINJA API key (keep this secure on server-side only)
const IPFS_API_KEY = 'bws_1234567890abcdef1234567890abcdef12345678';

// Generate a signed upload token
app.post('/api/generate-upload-token', async (req, res) => {
  try {
    const response = await fetch('https://api.ipfs.ninja/upload-tokens', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Api-Key': IPFS_API_KEY
      },
      body: JSON.stringify({
        expiresIn: '1h', // Token valid for 1 hour
        maxUploads: 10,  // Optional: limit number of uploads
        maxSizeMB: 50    // Optional: limit total upload size
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const tokenData = await response.json();
    
    res.json({
      success: true,
      uploadToken: tokenData.token,
      expiresAt: tokenData.expiresAt
    });
  } catch (error) {
    console.error('Token generation failed:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to generate upload token'
    });
  }
});

// Optional: Endpoint to verify uploads completed successfully
app.post('/api/verify-upload', async (req, res) => {
  const { cid } = req.body;
  
  try {
    // Verify the file was pinned successfully
    const response = await fetch(`https://api.ipfs.ninja/pins/${cid}`, {
      headers: {
        'X-Api-Key': IPFS_API_KEY
      }
    });

    const pinData = await response.json();
    
    res.json({
      success: true,
      verified: pinData.pinned,
      metadata: pinData
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: 'Verification failed'
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

前端实现:安全的客户端上传

现在,这是使用签名令牌安全上传文件的前端代码:

<!DOCTYPE html>
<html>
<head>
    <title>Secure IPFS Upload Demo</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
        .upload-area { border: 2px dashed #ccc; padding: 20px; text-align: center; margin: 20px 0; }
        .upload-area.dragover { border-color: #007cba; background: #f0f8ff; }
        button { background: #007cba; color: white; border: none; padding: 10px 20px; cursor: pointer; }
        .status { margin: 10px 0; padding: 10px; border-radius: 4px; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
    </style>
</head>
<body>
    <h1>Secure IPFS Upload with Signed Tokens</h1>
    
    <div class="upload-area" id="uploadArea">
        <p>Drag & drop files here or click to select</p>
        <input type="file" id="fileInput" multiple style="display: none;">
        <button onclick="document.getElementById('fileInput').click()">Select Files</button>
    </div>

    <div id="status"></div>
    <div id="results"></div>

    <script>
        class SecureIPFSUploader {
            constructor() {
                this.uploadToken = null;
                this.tokenExpiry = null;
                this.setupEventListeners();
            }

            setupEventListeners() {
                const uploadArea = document.getElementById('uploadArea');
                const fileInput = document.getElementById('fileInput');

                // Drag and drop handlers
                uploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    uploadArea.classList.add('dragover');
                });

                uploadArea.addEventListener('dragleave', () => {
                    uploadArea.classList.remove('dragover');
                });

                uploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    uploadArea.classList.remove('dragover');
                    this.handleFiles(Array.from(e.dataTransfer.files));
                });

                // File input handler
                fileInput.addEventListener('change', (e) => {
                    this.handleFiles(Array.from(e.target.files));
                });
            }

            async getUploadToken() {
                // Check if we have a valid token
                if (this.uploadToken && this.tokenExpiry && new Date() < new Date(this.tokenExpiry)) {
                    return this.uploadToken;
                }

                try {
                    this.showStatus('Generating secure upload token...', 'info');
                    
                    const response = await fetch('/api/generate-upload-token', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    if (!response.ok) {
                        throw new Error(`Failed to generate token: ${response.statusText}`);
                    }

                    const data = await response.json();
                    
                    if (!data.success) {
                        throw new Error(data.error || 'Token generation failed');
                    }

                    this.uploadToken = data.uploadToken;
                    this.tokenExpiry = data.expiresAt;
                    
                    return this.uploadToken;
                } catch (error) {
                    this.showStatus(`Token generation failed: ${error.message}`, 'error');
                    throw error;
                }
            }

            async uploadFile(file) {
                try {
                    const token = await this.getUploadToken();
                    
                    // Convert file to base64 for JSON transport
                    const fileBase64 = await this.fileToBase64(file);
                    
                    this.showStatus(`Uploading ${file.name} to IPFS...`, 'info');

                    const response = await fetch('https://api.ipfs.ninja/upload/new', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Signed ${token}`
                        },
                        body: JSON.stringify({
                            content: fileBase64,
                            description: `File uploaded via secure token: ${file.name}`,
                            metadata: {
                                filename: file.name,
                                fileType: file.type,
                                uploadedAt: new Date().toISOString(),
                                uploadMethod: 'signed-token'
                            }
                        })
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        throw new Error(`Upload failed: ${response.status} ${errorText}`);
                    }

                    const result = await response.json();
                    
                    return {
                        success: true,
                        filename: file.name,
                        cid: result.cid,
                        size: result.sizeMB,
                        ipfsUri: result.uris.ipfs,
                        httpUrl: result.uris.url
                    };
                } catch (error) {
                    return {
                        success: false,
                        filename: file.name,
                        error: error.message
                    };
                }
            }

            async handleFiles(files) {
                if (files.length === 0) return;

                this.clearResults();
                
                try {
                    // Upload files concurrently
                    const uploadPromises = files.map(file => this.uploadFile(file));
                    const results = await Promise.all(uploadPromises);
                    
                    this.displayResults(results);
                    
                    const successful = results.filter(r => r.success).length;
                    const total = results.length;
                    
                    if (successful === total) {
                        this.showStatus(`✅ Successfully uploaded ${successful} file(s) to IPFS!`, 'success');
                    } else {
                        this.showStatus(`⚠️ Uploaded ${successful}/${total} files. Check results below.`, 'error');
                    }
                } catch (error) {
                    this.showStatus(`Upload failed: ${error.message}`, 'error');
                }
            }

            fileToBase64(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => {
                        // Remove the data:mime/type;base64, prefix
                        const base64 = reader.result.split(',')[1];
                        resolve(base64);
                    };
                    reader.onerror = error => reject(error);
                });
            }

            showStatus(message, type) {
                const statusDiv = document.getElementById('status');
                statusDiv.className = `status ${type}`;
                statusDiv.textContent = message;
            }

            displayResults(results) {
                const resultsDiv = document.getElementById('results');
                
                resultsDiv.innerHTML = '<h3>Upload Results:</h3>' + 
                    results.map(result => `
                        <div class="status ${result.success ? 'success' : 'error'}" style="margin: 10px 0;">
                            <strong>${result.filename}</strong><br>
                            ${result.success ? 
                                `✅ CID: ${result.cid}<br>
                                 📊 Size: ${result.size} MB<br>
                                 🔗 URL: <a href="${result.httpUrl}" target="_blank">${result.httpUrl}</a>` :
                                `❌ Error: ${result.error}`
                            }
                        </div>
                    `).join('');
            }

            clearResults() {
                document.getElementById('results').innerHTML = '';
            }
        }

        // Initialize the uploader
        const uploader = new SecureIPFSUploader();
    </script>
</body>
</html>

高级安全注意事项

在使用签名令牌实现 IPFS 上传安全时,请考虑以下额外的安全措施:

令牌范围限制

使用适当的限制配置令牌:

// Generate token with specific constraints
const restrictedToken = await fetch('https://api.ipfs.ninja/upload-tokens', {
  method: 'POST',
  headers: {
    'X-Api-Key': IPFS_API_KEY
  },
  body: JSON.stringify({
    expiresIn: '30m',        // Short expiration
    maxUploads: 5,           // Limited upload count
    maxSizeMB: 10,          // Size restriction
    allowedMimeTypes: ['image/jpeg', 'image/png'], // File type restrictions
    ipWhitelist: ['192.168.1.0/24'] // IP-based access control
  })
});

内容验证

始终在后端验证上传的内容:

app.post('/api/validate-upload', async (req, res) => {
  const { cid } = req.body;
  
  try {
    // Fetch and validate the uploaded content
    const response = await fetch(`https://ipfs.ninja/ipfs/${cid}`);
    const contentType = response.headers.get('content-type');
    
    // Implement your validation logic
    if (!isValidContentType(contentType)) {
      // Remove invalid content
      await deleteFromIPFS(cid);
      return res.status(400).json({ error: 'Invalid content type' });
    }
    
    res.json({ success: true, validated: true });
  } catch (error) {
    res.status(500).json({ error: 'Validation failed' });
  }
});

速率限制

在令牌生成端点上实施额外的速率限制:

const rateLimit = require('express-rate-limit');

const tokenLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 10, // Limit each IP to 10 token requests per windowMs
  message: 'Too many token requests, please try again later'
});

app.use('/api/generate-upload-token', tokenLimiter);

相比传统方法的优势

签名上传令牌相比其他 IPFS 上传安全方法具有多项优势:

与服务器端代理相比

  • 性能:直接上传消除了服务器带宽占用
  • 可扩展性:高上传量期间无服务器瓶颈
  • 成本:减少带宽和处理成本
  • 用户体验:更快的上传速度和进度跟踪

与客户端 API 密钥相比

  • 安全性:无 API 密钥被提取或滥用的风险
  • 合规性:满足安全审计要求
  • 访问控制:细粒度权限和自动过期
  • 监控:更好地跟踪上传来源和模式

与其他固定服务相比

IPFS.NINJA 目前是唯一提供签名上传令牌的主要固定服务。像 Pinata 这样的竞争对手要求服务器端代理或客户端 API 密钥暴露,这使得此功能成为独特的差异化优势。

有关 IPFS.NINJA 与其他服务的比较详情,请查看我们的全面比较指南

生产部署提示

在生产环境中部署签名上传令牌时:

环境配置

安全地存储敏感配置:

// Use environment variables for production
const config = {
  ipfsApiKey: process.env.IPFS_API_KEY,
  tokenExpiry: process.env.UPLOAD_TOKEN_EXPIRY || '1h',
  maxFileSize: process.env.MAX_FILE_SIZE_MB || 50,
  allowedOrigins: process.env.ALLOWED_ORIGINS?.split(',') || ['localhost:3000']
};

监控和日志记录

实施全面的日志记录以进行安全监控:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'upload-security.log' })
  ]
});

// Log token generation
logger.info('Upload token generated', {
  userId: req.user.id,
  clientIP: req.ip,
  userAgent: req.get('User-Agent'),
  expiresAt: tokenData.expiresAt
});

错误处理

实施健壮的错误处理,不泄露敏感信息:

app.use((error, req, res, next) => {
  // Log full error details server-side
  logger.error('Upload token error', {
    error: error.message,
    stack: error.stack,
    userId: req.user?.id,
    endpoint: req.path
  });
  
  // Send safe error message to client
  res.status(500).json({
    success: false,
    error: 'An internal error occurred. Please try again.'
  });
});

与流行框架集成

签名上传令牌可以与现代 Web 框架无缝集成。以下是快速集成示例:

React Hook

import { useState, useCallback } from 'react';

export function useSecureIPFSUpload() {
  const [uploading, setUploading] = useState(false);
  const [uploadToken, setUploadToken] = useState(null);

  const getToken = useCallback(async () => {
    if (uploadToken?.expiresAt && new Date() < new Date(uploadToken.expiresAt)) {
      return uploadToken.token;
    }

    const response = await fetch('/api/generate-upload-token', {
      method: 'POST'
    });
    const data = await response.json();
    setUploadToken(data);
    return data.uploadToken;
  }, [uploadToken]);

  const uploadFile = useCallback(async (file) => {
    setUploading(true);
    try {
      const token = await getToken();
      // Upload logic here...
    } finally {
      setUploading(false);
    }
  }, [getToken]);

  return { uploadFile, uploading };
}

Vue.js Composable

import { ref } from 'vue';

export function useSecureUpload() {
  const uploading = ref(false);
  const uploadProgress = ref(0);

  const uploadFile = async (file) => {
    uploading.value = true;
    // Implementation here...
  };

  return {
    uploading: readonly(uploading),
    uploadProgress: readonly(uploadProgress),
    uploadFile
  };
}

结论

签名上传令牌解决了去中心化应用开发中的一个关键安全挑战。通过提供一种安全的方式来实现直接客户端到 IPFS 的上传,而无需暴露 API 密钥,它们为现代 Web 应用程序开辟了新的架构可能性。

无论您是在构建内容管理系统、NFT 市场,还是任何需要安全文件上传的应用程序,IPFS.NINJA 的上传令牌都能提供您所需的安全性和灵活性。实现过程简单直接,安全收益显著,性能提升明显。

要了解更多关于 IPFS 基础知识,请查看我们的什么是 IPFS 固定指南,或浏览我们的完整 API 教程。对于正在评估不同选项的开发者,我们的最佳 IPFS 固定服务比较提供了全面的洞察。

准备好在您的应用程序中实现安全的客户端 IPFS 上传了吗?现代安全实践与去中心化存储的结合使这种方法成为需要在保持安全标准的同时进行扩展的生产应用程序的理想选择。

准备好开始固定了吗? 创建免费账户 — 500 个文件,1 GB 存储,专用网关。无需信用卡。

返回博客