python-3.x - 在 Python 中签署 SAML 响应
问题描述
我需要签署一个 SAML 断言,因为它可以在此页面上执行: https ://www.samltool.com/sign_response.php
就我而言,我使用的是 Python,而我的 SAML 位于字符串中。
你有什么建议?
此致,
尼科。
解决方案
我终于使用signxml lib做到了。
提醒一下,我想签署 SAML 断言。
我从文件中获取未签名的 SAML。然后我将这个标签 <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder"></ds:Signature> 放在 Issuer 标签和 Subject 标签之间,正如signxml lib推荐的那样。最后,我签署我的 SAML 并验证签名。请注意,我更改了 c14n_algorithm 以与我的服务兼容。
这是代码:
import re
from lxml import etree
from signxml import XMLSigner, XMLVerifier
with open('saml_to_sign.xml', 'r') as file :
data_to_sign = file.read()
with open("/vagrant/my_cert.crt", "r") as cert,\
open("/vagrant/my_key.key", "r") as key:
certificate = cert.read()
private_key = key.read()
p = re.search('<Subject>', data_to_sign).start()
tmp_message = data_to_sign[:p]
tmp_message = tmp_message +\
'<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="placeholder"></ds:Signature>'
data_to_sign = tmp_message + data_to_sign[p:]
print(data_to_sign)
saml_root = etree.fromstring(data_to_sign)
signed_saml_root = XMLSigner(c14n_algorithm="http://www.w3.org/2001/10/xml-exc-c14n#")\
.sign(saml_root, key=private_key, cert=certificate)
verified_data = XMLVerifier().verify(signed_saml_root, x509_cert=certificate).signed_xml
signed_saml_root_str = etree.tostring(signed_saml_root, encoding='unicode')
print(signed_saml_root_str)
推荐阅读
- python - 嵌套函数返回外部函数
- javascript - 如何处理使用“等待”的嵌套异步函数中的异常
- matlab - 使用 MATLAB cell2mat() 函数时出现大括号索引错误
- clojure - Clojure 领域建模:规范与协议
- c++ - vector.push_back 不起作用![运行时错误]
- python - Python Selenium Web Scrape 将 XPATH 中的 csv/excel 文件嵌入到 pandas 数据帧
- spring - 我越来越无法获取 JDBC 连接异常
- python - 使用python将信息从Linux文件解析到Windows
- ansible - Ansible 从结果中检索多个数组值
- pyspark - 如何在 PySpark collect_list 中维护排序顺序并收集多个列表