基于 HTTPS 保护的 API

最近部署了 ELK,KubeSphere,发现好多东西都在使用自签发的证书,并且现在HTTPS的网站覆盖率已经非常非常高了。

既然 HTTPS 这么好用,能不能解决更多问题呢。

我经常遇到一个场景,现代微服务应用,很多服务的职责非常清晰,只提供一个功能,一两个接口。

那么为了这一个接口而设计 各种权限认证 或者 Token 校验,显得非常罗嗦 麻烦。

但苦于一直没有找到轻量化的方案,所以一般情况下 我更多的选择是 IP Allow List。

但 我觉得 这个解,非 HTTPS 不可。

HTTPS

生成证书

mkdir -p certs

openssl req \
-newkey rsa:4096 -nodes -sha256 -keyout certs/domain.key \
-x509 -days 36500 -out certs/domain.crt

nginx config

server {
	listen 443 default_server;
	listen [::]:443 default_server;

	ssl on;
	ssl_certificate /etc/nginx/certs/domain.crt;
	ssl_certificate_key /etc/nginx/certs/domain.key;
	ssl_client_certificate /etc/nginx/certs/domain.crt;
	
	ssl_verify_client on;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

	root /var/www/html;

	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html;

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}
}

test

curl --key certs/domain.key --cert certs/domain.crt https://192.168.1.127

IP Allow List

old way.

get ip

curl ipconfig.io

nginx config

# permit ip list
location /api/permitlist/internal {
    allow 192.168.1.128;
    allow 127.0.0.1;
    deny  all;
    proxy_pass http://backend;
}

Tips

如何跳过 HTTPS 验证

curl -k https://192.168.1.127

如何防止跳过 HTTPS 验证

nginx 来举例,一定要配置 ssl_verify_client on

curl SSL certificate problem

curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

信任 自签发证书即可

cp domain.crt /usr/local/share/ca-certificates/
update-ca-certificates

Refs: