如何在Heroku Node Express应用程序中使用LetsEncrypt SSL证书?

sto*_*one 13 ssl heroku node.js express lets-encrypt

我有一个在Heroku上运行的Node Express应用程序,我希望使用LetsEncrypt的免费SSL证书进行加密.但是,我看到的方法需要打开端口443和80以允许ACME进程工作.

Heroku只给你一个端口,不允许你选择哪个端口.那么我该如何使用LetsEncrypt呢?

昨天我花了很多时间搞清楚这一点.很久以来第一次在StackOverflow上找不到我想做的事情的答案!

sto*_*one 19

更新:

Heroku现在本地支持LetsEncrypt!因此不再需要此解决方法.

说明:

https://devcenter.heroku.com/articles/automated-certificate-management

对于新应用,您无需执行任何操作,默认情况下已启用此功能.对于2017年3月21日之前创建的应用程序,您可以使用此Heroku cli命令将其打开: heroku certs:auto:enable

谢谢@Spain Train


背景

理想情况下,LetsEncrypt允许自动证书续订过程.这在Heroku上很难做到,所以这个答案描述了如何使用手动过程.使用Heroku环境var,您将能够非常轻松地手动更新证书 - 无需更改代码.

这个答案很有用,主要归功于两篇不错的博文: https://medium.com/@franxyzxyz/setting-up-free-https-with-heroku-ssl-and-lets-encrypt-80cf6eac108e#.67pjxutaw

https: //medium.com/should-designers-code/how-to-set-up-ssl-with-lets-encrypt-on-heroku-for-free-266c185630db#.ldr9wrg2j

有一个GitHub项目显然支持Heroku上的自动化证书更新.我试用时会更新这个答案:https:
//github.com/dmathieu/sabayon

使用Node Express应用程序在Heroku上使用LetsEncrypt

准备好Express服务器:

将此中间件添加到Express应用程序中.确保在将http重定向到https的任何中间件之前添加它,因为此端点必须是http.

// Read the Certbot response from an environment variable; we'll set this later:

const letsEncryptReponse = process.env.CERTBOT_RESPONSE;

// Return the Let's Encrypt certbot response:
app.get('/.well-known/acme-challenge/:content', function(req, res) {
  res.send(letsEncryptReponse);
});
Run Code Online (Sandbox Code Playgroud)

使用certbot创建证书文件:

  1. 启动certbot: sudo certbot certonly --manual
    在提示时输入站点URL(www.example.com)
    certbot将显示质询
    xxxxxxxxxxxxxxxxxxx.yyyyyyyyyyyyyyyyyy
    在此状态下等待CERTBOT的挑战响应字符串.不要按Enter键或退出.
  2. 转到Heroku仪表板并查看应用程序设置:
    https: //dashboard.heroku.com/apps/your-heroku-app-name/settings
    在Config Variables下,单击'显示配置变量'
    编辑CERTBOT_RESPONSE var的值以匹配挑战来自步骤a的回应.
  3. 等待heroku应用程序重新启动.
  4. 通过访问http://www.example.com/.well-known/acme-challenge/whatever来测试设置 .
    注意HTTP,而不是HTTPS
    它应该显示Challenge Response字符串.如果发生这种情况,请继续执行下一步.如果没有,请在继续操作之前尽一切努力使该URL返回CR字符串,否则您将需要重复此整个过程.
  5. 返回Certbot并按Enter继续.
    如果一切按计划进行,certbot会告诉您一切正常并显示创建的证书的位置.您将在下一步中使用此位置.请注意,由于os权限,您可能无法检查文件夹的内容.如有疑问,sudo ls /etc/letsencrypt/live/www.example.com请查看文件是否存在.

更新Heroku实例以使用新证书:

运行heroku certs:add如果您的网站没有证书.如果更新,请运行heroku certs:update.
sudo heroku certs:update --app your-heroku-app-name /etc/letsencrypt/live/www.example.com/fullchain.pem /etc/letsencrypt/live/www.example.com/privkey.pem