Skip to content

n8n 安全最佳实践 - 保护自动化系统

安全是企业级自动化系统的重要基石。本文将介绍 n8n 的安全配置、数据保护、访问控制等关键安全实践。

认证与授权

基本认证配置

bash
# 环境变量配置
N8N_BASIC_AUTH_ACTIVE=true
N8N_BASIC_AUTH_USER=admin
N8N_BASIC_AUTH_PASSWORD=secure_password_123

OAuth2 集成

javascript
// OAuth2 配置示例
const oauthConfig = {
  clientId: process.env.OAUTH_CLIENT_ID,
  clientSecret: process.env.OAUTH_CLIENT_SECRET,
  redirectUri: 'https://your-n8n.com/oauth/callback',
  scope: 'read write'
};

数据加密与保护

敏感数据处理

javascript
// 敏感数据加密
const crypto = require('crypto');

function encryptSensitiveData(data, key) {
  const cipher = crypto.createCipher('aes-256-cbc', key);
  let encrypted = cipher.update(data, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return encrypted;
}

function decryptSensitiveData(encryptedData, key) {
  const decipher = crypto.createDecipher('aes-256-cbc', key);
  let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

凭证管理

javascript
// 安全的凭证存储
class SecureCredentialManager {
  constructor(encryptionKey) {
    this.encryptionKey = encryptionKey;
  }
  
  storeCredential(name, credential) {
    const encrypted = this.encrypt(JSON.stringify(credential));
    // 存储到安全的存储系统
    return this.saveToSecureStorage(name, encrypted);
  }
  
  retrieveCredential(name) {
    const encrypted = this.getFromSecureStorage(name);
    const decrypted = this.decrypt(encrypted);
    return JSON.parse(decrypted);
  }
}

网络安全

HTTPS 配置

nginx
# Nginx 配置
server {
    listen 443 ssl http2;
    server_name your-n8n.com;
    
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
    
    location / {
        proxy_pass http://localhost:5678;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

防火墙配置

bash
# UFW 防火墙规则
ufw allow 22/tcp    # SSH
ufw allow 443/tcp   # HTTPS
ufw deny 5678/tcp   # 阻止直接访问 n8n 端口
ufw enable

访问控制

基于角色的访问控制

javascript
// RBAC 实现
class RoleBasedAccessControl {
  constructor() {
    this.roles = {
      admin: ['read', 'write', 'delete', 'manage_users'],
      editor: ['read', 'write'],
      viewer: ['read']
    };
  }
  
  hasPermission(userRole, action) {
    return this.roles[userRole]?.includes(action) || false;
  }
  
  checkWorkflowAccess(user, workflow, action) {
    // 检查用户是否有权限访问特定工作流
    if (!this.hasPermission(user.role, action)) {
      throw new Error('Access denied');
    }
    
    // 检查工作流所有权
    if (workflow.owner !== user.id && user.role !== 'admin') {
      throw new Error('Insufficient permissions');
    }
    
    return true;
  }
}

审计日志

操作日志记录

javascript
// 审计日志系统
class AuditLogger {
  constructor() {
    this.logLevel = process.env.AUDIT_LOG_LEVEL || 'info';
  }
  
  logWorkflowExecution(workflowId, userId, action, result) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      type: 'workflow_execution',
      workflowId,
      userId,
      action,
      result: result.success ? 'success' : 'failure',
      duration: result.duration,
      ip: this.getClientIP(),
      userAgent: this.getUserAgent()
    };
    
    this.writeLog(logEntry);
  }
  
  logUserAction(userId, action, resource, details) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      type: 'user_action',
      userId,
      action,
      resource,
      details,
      ip: this.getClientIP()
    };
    
    this.writeLog(logEntry);
  }
  
  writeLog(entry) {
    // 写入到安全的日志存储
    console.log(JSON.stringify(entry));
  }
}

小结

安全是自动化系统的基础,需要从多个层面进行保护:

  1. 认证授权:确保只有授权用户可以访问
  2. 数据保护:加密敏感数据和凭证
  3. 网络安全:使用 HTTPS 和防火墙保护
  4. 访问控制:实施细粒度的权限管理
  5. 审计监控:记录和监控所有操作

下一篇文章将学习部署与运维,了解如何在生产环境中稳定运行 n8n。