簡體   English   中英

如何使用 Python 連接到需要客戶端證書的 websocket

[英]How to connect to a websocket that requires client-certificate using Python

我正在使用 Python 的websockets使用基本身份驗證連接到 websocket 服務器。 服務器現在要求我提供一個 P12 格式的 ssl/tls 客戶端證書。

如何配置我的 websockets 客戶端以使用 P12 文件中的證書?

首先我必須從P12文件中提取證書和密鑰。 假設我的客戶端證書以 P12 格式存儲在一個名為cert.p12的文件中,我使用 openssl 提取證書和密鑰(openssl 將提示輸入證書的密碼):

    openssl pkcs12 -in cert.p12 -out cert.pem -clcerts -nokeys
    openssl pkcs12 -in cert.p12 -out cert.keys -nocerts

現在,在 Python 中:

import asyncio
import pathlib
import ssl

import websockets

username = "..."
password = "..."
host = "..."
url = f"wss://{username}:{password}@{host}/..."


ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context.load_default_certs()
ssl_context.load_cert_chain(
    pathlib.Path("cert.pem"),
    pathlib.Path("cert.keys"),
    "..."  # The certificate's password goes here
)


async def consume():
    try:
        async with websockets.connect(uri=url, ssl=ssl_context) as websocket:
            async for message in websocket:
                print(message)
    except Exception as e:
        print(e)


async def main():
    await asyncio.gather(consume())


asyncio.get_event_loop().run_until_complete(main())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM