处理服务器 SSL 证书所需的文件

Files needed to handle SSL Certificate of Server

我有一个虚拟机。我生成了 SSL 证书:

openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365

之后使用带有参数 ssl_context:

的 Flask 编写了一个网络服务器
from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/")
def index():
    return "Flask is running!"


@app.route("/data")
def some_func():
    pass

if __name__ == "__main__":
    app.run(ssl_context=("cert.pem", "key.pem"))

现在我在同一个网络中有另一个虚拟机,我有一个请求一些数据的客户端应用程序:

import requests
import json

SERVER_URL = 'https://example.com/data'

token = "some_token"

def _send():
    query = """some_query"""

    data = {'query': query}

    headers = {'Accept': 'application/json',
               'Content-Type': 'application/json',
               'Authorization': "Bearer %s" % token
               }

    response = requests.post(SERVER_URL,
                             data=json.dumps(data).encode('utf-8'),
                             headers=headers,
                             verify=Flase)
    if response.status_code == 200:
        res = json.loads(response.text)
        return True, res, None
    return False, None, response.text


print(_send())

我现在需要的是将一些证书的参数路径传递给 verify,这将帮助我检查服务器的 SSL 证书。但是我需要传递哪些文件来验证?我生成并传递给 Flask 应用程序的 cert.pemkey.pemssl_contextor 相同,或者我需要生成另一个文件(如果是,我如何 generate/create 该文件)?

我稍微修改了你的例子:

  1. 使用 CommonNameSubjectAltName 生成证书(在这个例子中我使用了 domain.test):
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365 -subj /CN=domain.test -addext "subjectAltName = DNS:domain.test"
  1. 运行 服务器部分的代码:
from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/")
def index():
    return "Flask is running!"


@app.route("/data", methods=["GET", "POST"])  # <-- add methods= here
def some_func():
    return jsonify({"result": "Hello World!"})  # <-- return some example data


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, ssl_context=("cert.pem", "key.pem"))
  1. 客户端部分:
import requests
import json

SERVER_URL = "https://domain.test:5000/data"  # <-- put domain.test here

token = "some_token"


def _send():
    query = """some_query"""

    data = {"query": query}

    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": "Bearer %s" % token,
    }

    response = requests.post(
        SERVER_URL,
        data=json.dumps(data).encode("utf-8"),
        headers=headers,
        verify="cert.pem",  # <-- put cert.pem here
    )

    if response.status_code == 200:
        res = json.loads(response.text)
        return True, res, None

    return False, None, response.text


print(_send())

没有任何警告的输出:

(True, {'result': 'Hello World!'}, None)