为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Python 解码“X-ARR-ClientCert”标头?

如何使用 Python 解码“X-ARR-ClientCert”标头?

梦里花落0921 2023-10-31 14:17:49
如何解码X-ARR-ClientCertAzure 应用服务传递到我的 Azure Function 代码的标头?例子:HTTP 触发的 Python Azure FunctionAzure 应用服务配置为接受客户端证书请求者通过 GET 请求发送客户端证书(按照此处的 Postman 说明)X-ARR-ClientCertAzure 应用服务通过标头将客户端证书传递给函数代码问题:我找不到有关如何编码此标头的文档我找不到如何使用 Python 解码此标头的示例我得到的最接近的是这段代码:import loggingimport base64import azure.functions as funcdef main(req: func.HttpRequest) -> func.HttpResponse:        logging.info('####### Python HTTP trigger certificate validation function processing a request. #######')    # Retrieve client cert from headers    req_cert_str = req.headers.get("X-ARR-ClientCert")        req_cert_bytes = base64.b64decode(req_cert_str)        decoded_string = req_cert_bytes.decode('cp1252')    return func.HttpResponse(        decoded_string    )结果是Status 500 Internal server error:Exception while executing function: Functions.certiFunc <--- Result: Failure Exception: UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 403: character maps to <undefined> Stack: File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 343, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.8/LINUX/X64/azure_functions_worker/dispatcher.py", line 480, in __run_sync_func return func(**params) File "/home/site/wwwroot/certiFunc/__init__.py", line 14, in main decoded_string = req_cert_bytes.decode('cp1252') File "/usr/local/lib/python3.8/encodings/cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) 当替换 时decoded_string = req_cert_bytes.decode('utf-8'),我得到:运行以下命令时(直接解码标头)...req_cert_str = req.headers.get("X-ARR-ClientCert")decoded_string = base64.b64decode(req_cert_str) ...我得到一个Status 200 Success,但响应是二进制(?)字符和纯文本的混搭:
查看完整描述

1 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

由于您要从 Postman 添加客户端证书,因此它采用 DER(二进制)格式。您可以使用 Python加密技术从字节本身解码 x509 证书。


from cryptography import x509


# header is base64 encoded string, so extract the bytes first

req_cert_str = req.headers.get("X-ARR-ClientCert") 

req_cert_bytes = base64.b64decode(req_cert_str)


cert = x509.load_der_x509_certificate(req_cert_bytes)


# do stuffs with cert

logging.info(f'Received client cert with serial number: {cert.serial_number}')


查看完整回答
反对 回复 2023-10-31
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信