---
title: "用Nginx设置密码来保护以太坊JSON-RPC的API"
author: "it_node"
date: "2018-10-29T09:30:30Z"
tags: []
categories: ["开源软件"]
slug: "nginx-json-rpc-api"
draft: false
lastmod: "2018-10-29T09:30:30Z"
id: 2432873
url: "https://it-node.iteye.com/blog/2432873"
---

本文面向以太坊智能合约应用程序开发人员，并讨论如何在密码保护后，安全地运行你的以太坊节点，以便通过Internet进行安全输出。

Go Ethereum（geth）是以太坊节点最受欢迎的软件。其他流行的以太坊实现是Parity和cpp-ethereum等。分布式应用程序（Dapps）是JavaScript编码的网页，通过JSON-RPC API协议连接到任何这些以太坊节点软件，该协议是在HTTP协议之上自行运行的。

geth或没有节点软件本身不提供安全网络。将Ethereum JSON-RPC API暴露给公共Internet是不安全的，因为即使禁用私有API，这也会为琐碎的拒绝服务攻击打开一扇门。节点软件本身不需要提供安全的网络原语，因为这种内置功能会增加复杂性并为关键区块链节点软件增加攻击面。

Dapps本身是纯客户端HTML和JavaScript，不需要任何服务器，它们可以在任何Web浏览器中运行，包括移动和嵌入式浏览器，如Mist钱包内的一个。

### 使用Nginx代理作为HTTP基本身份验证器

有几种方法可以保护对HTTP API的访问。最常见的方法包括HTTP头中的API令牌，基于cookie的身份验证或[HTTP基本访问身份验证](https://en.wikipedia.org/wiki/Basic_access_authentication)。

HTTP基本身份验证是HTTP协议的一个非常古老的功能，其中Web浏览器打开一个本机弹出对话框，询问用户名和密码。它本质上的保护是有限的，但非常容易实现，非常适合需要为有限的互联网受众暴露私有Dapp的用例。这些用例包括显示Dapp演示，私有和许可的区块链应用程序或将以太坊功能作为软件即服务解决方案的一部分。

### Nginx

[Nginx](http://nginx.org/)是最受欢迎的开源Web服务器应用程序之一。我们将展示如何设置Nginx Web服务器，以便它使用HTTP Basic Auth私下为你的Dapp（HTML文件）和geth JSON-RPC API提供服务。

我们假设Ubuntu 14.04更新的Linux服务器。文件位置可能取决于使用的Linux发行版。

### 安装Nginx

在Ubuntu Linux 14.04或更高版本上安装Nginx：

```
sudo apt install nginx apache2-utils
```

### 配置Nginx

我们假设我们编辑默认的网站配置文件`/etc/nginx/sites-enabled/default`。我们使用[proxy\_pass指令](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass)与在`localhost:8545`中运行的geth进行通信：

```
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;
    server_name demo.example.com;


    # Geth proxy that password protects the public Internet endpoint
    location /eth {
        auth_basic "Restricted access to this site";
        auth_basic_user_file /etc/nginx/protected.htpasswd;

        # Proxy to geth note that is bind to localhost port                        
        proxy_pass http://localhost:8545;            
    }

    # Server DApp static files
    location / {
        root /usr/share/nginx/html;
        index index.html

        auth_basic "Restricted access to this site";
        auth_basic_user_file /etc/nginx/protected.htpasswd;
    }       
}
```

使用密码创建HTTP Basic Auth用户演示：

```
sudo htpasswd -c /etc/nginx/protected.htpasswd demo
```

### 配置geth

开始使用geth守护进程的最简单方法是在UNIX [screen](http://www.thegeekstuff.com/2010/07/screen-command-examples)中运行它：

```
screen

geth  # Your command line parameters here
```

退出`screen` 使用`CTRL+A, D`。

[请参阅geth private testnet说明](http://ethereum.stackexchange.com/questions/125/how-do-i-set-up-a-private-ethereum-network)

### 配置Dapp

在你的Dapp中，使web3.js使用`/eth`端点：

```
  function getRPCURL() {

    // ES2016 
    if(window.location.href.includes("demo.nordledger.com")) {      
      // Password protected geth deployment
      return "http://demo.nordledger.com/eth"

    } else {
        // Localhost development
      return "http://localhost:8545";  
    }
  }

  // ...

  web3.setProvider(new web3.providers.HttpProvider(getRPCURL()));
```

### 部署Dapp

将DApp文件复制到服务器上的`/usr/share/nginx/html`。这包括index.html以及相关的JavaScript和CSS资源。

Bonus - 部署shell脚本示例：

```
#!/bin/bash
#
# A simple static HTML + JS deployment script that handles Nginx www-data user correclty.
# Works e.g. Ubuntu Linux Azure and Amazon EC2 Ubuntu server out of the box.
#

set -e
set -u

# The remote server we are copying the files using ssh + public key authentication.
# Specify this in .ssh/config
REMOTE="nordledger-demo"

# Build dist folder using webpack
npm run build

# Copy local dist folder to the remote server Nginx folder over sudoed
# Assum the default user specified in .ssh/config has passwordless sudo
# https://crashingdaily.wordpress.com/2007/06/29/rsync-and-sudo-over-ssh/
rsync -a -e "ssh" --rsync-path="sudo rsync" dist/* --chown www-data:www-data $REMOTE:/usr/share/nginx/html/
```

### 重启Nginx

为Nginx做一次硬重启：

```
service nginx stop service nginx start
```

### 测试并迭代

访问网站，看看您的Dapp是否连接到代理的Geth。

检查`/var/log/nginx/error.log`以获取详细信息。

如果从`/eth`端点获得502 Bad Gateway，请确保geth正在作为服务器上的后台进程正常运行。

 

分享一些以太坊、EOS、比特币等区块链相关的交互式在线编程实战教程：

> - [java以太坊开发教程](http://xc.hubwiz.com/course/5b2b6e82c02e6b6a59171de2?affid=1029iteye)，主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
> - [python以太坊](http://xc.hubwiz.com/course/5b40462cc02e6b6a59171de4?affid=1029iteye)，主要是针对python工程师使用web3.py进行区块链以太坊开发的详解。
> - [php以太坊](http://xc.hubwiz.com/course/5b36629bc02e6b6a59171de3?affid=1029iteye)，主要是介绍使用php进行智能合约开发交互，进行账号创建、交易、转账、代币开发以及过滤器和交易等内容。
> - [以太坊入门教程](http://xc.hubwiz.com/course/5a952991adb3847553d205d1?affid=1029iteye)，主要介绍智能合约与dapp应用开发，适合入门。
> - [以太坊开发进阶教程](http://xc.hubwiz.com/course/5abbb7acc02e6b6a59171dd6?affid=1029iteye)，主要是介绍使用node.js、mongodb、区块链、ipfs实现去中心化电商DApp实战，适合进阶。
> - [C#以太坊](http://xc.hubwiz.com/course/5b6048c3c02e6b6a59171dee?affid=1029oschina)，主要讲解如何使用C#开发基于.Net的以太坊应用，包括账户管理、状态与交易、智能合约开发与交互、过滤器和交易等。
> - [EOS教程](http://xc.hubwiz.com/course/5b52c0a2c02e6b6a59171ded?affid=1029iteye)，本课程帮助你快速入门EOS区块链去中心化应用的开发，内容涵盖EOS工具链、账户与钱包、发行代币、智能合约开发与部署、使用代码与智能合约交互等核心知识点，最后综合运用各知识点完成一个便签DApp的开发。
> - [java比特币开发教程](http://xc.hubwiz.com/course/5bb35c90c02e6b6a59171df0?affid=1029iteye)，本课程面向初学者，内容即涵盖比特币的核心概念，例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等，同时也详细讲解如何在Java代码中集成比特币支持功能，例如创建地址、管理钱包、构造裸交易等，是Java工程师不可多得的比特币开发学习课程。
> - [php比特币开发教程](http://xc.hubwiz.com/course/5b9e779ac02e6b6a59171def?affid=1029iteye)，本课程面向初学者，内容即涵盖比特币的核心概念，例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等，同时也详细讲解如何在Php代码中集成比特币支持功能，例如创建地址、管理钱包、构造裸交易等，是Php工程师不可多得的比特币开发学习课程。

这里是[原文](http://blog.hubwiz.com/2018/10/28/ethereum-json-rpc-api-password/)