基于Let’s Encrypt证书实现nginx https双向认证
第一步,先基于Let’s Encrypt证书配置https单向校验的网站出来先
wget https://dl.eff.org/certbot-auto
chmod u+x certbot-auto
./certbot-auto certonly --standalone -m abc@yubangweb.com --agree-tos -d abc.yubangweb.com
修改nginx的配置
server {
listen 80;
listen 443 ssl;
server_name abc.yubangweb.com;
root /var/web;
ssl_certificate /etc/letsencrypt/live/abc.yubangweb.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/abc.yubangweb.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/abc.yubangweb.com/chain.pem;
location / {
}
}
然后打开浏览器,访问:https://abc.yubangweb.com/
这个时候就配置好了单向校验的https网站
第二步,就是自签客户端证书
# 签服务端证书
openssl genrsa -des3 -out ca.key 4096
openssl genrsa -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.crt
# 签客户端证书
openssl genrsa -out client.key 4096
openssl req -new -key client.key -out client.csr
openssl x509 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt
openssl pkcs12 -export -clcerts -in client.crt -inkey client.key -out client.p12
openssl pkcs12 -in client.p12 -out all.pem -nodes
第三步,nginx启用客户端证书校验
# 在刚才的配置文件添加这两行
ssl_client_certificate /root/ssl/ca.crt;
ssl_verify_client on;
测试一下客户端证书是否生效(在其它机器执行下面命令)
# 注意复制上面生成的all.pem文件
curl -k --cert all.pem https://abc.yubangweb.com
完整的nginx配置:
server {
listen 80;
listen 443 ssl;
server_name abc.yubangweb.com;
root /var/web;
ssl_certificate /etc/letsencrypt/live/abc.yubangweb.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/abc.yubangweb.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/abc.yubangweb.com/chain.pem;
ssl_client_certificate /root/ssl/ca.crt;
ssl_verify_client on;
location / {
}
}
如果需要控制某些请求需要客户端证书校验,则使用下列方法
server {
listen 80;
listen 443 ssl;
server_name abc.yubangweb.com;
root /var/web;
ssl_certificate /etc/letsencrypt/live/abc.yubangweb.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/abc.yubangweb.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/abc.yubangweb.com/chain.pem;
ssl_client_certificate /root/ssl/ca.crt;
ssl_verify_client optional;
location / {
if ($ssl_client_verify != SUCCESS) {
return 401;
}
}
location /abc {
}
}