[英]Bearer Token authorization header in SOAP client with Zeep and Python
一般來說,我是 SOAP 請求和編程的新手。 我想訪問需要 Bearer Token Authorization 才能使用其中一項服務的 WSDL。
有關調用pyhton -mzeep *WSDL_url*
后我想訪問的服務的信息:
getInfo(param1: xsd:string, param2: xsd:anySimpleType, param3: xsd:anySimpleType) -> out: ns0:ResponseCurve[]
首先我收到令牌:
import zeep
user = 'my_user'
userpass = 'my_pass'
token = client.service.getAuthToken(user,userpass)
然后我想請求需要三個參數的服務getInfo:
my_info = client.service.getInfo('param1', 'param2', 'param3')
我從提供者那里知道每次我想訪問此服務時都需要令牌,並且在文檔中對有關身份驗證的標頭進行了說明:
授權:承載 eyJhbGciOiJIUzI1N[...]
我試圖在_soapheaders
標頭作為字典傳遞,但沒有用。
我可以使用強制請求訪問該服務:
def get_response_from_provider(token, param1, param2, param3):
url = "WSDL url"
headers = {'Authorization': 'Bearer ' + token,
'content-type': 'text/xml'}
body = """
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsl="uri">
<soapenv:Header/>
<soapenv:Body>
<wsl:getInfo>
<param1>""" + param1 + """</param1>
<param2>""" + param2 + """ </param2>
<param3>""" + param3 + """ </param3>
</wsl:getInfo>
</soapenv:Body>
</soapenv:Envelope>"""
response = requests.post(url, data=body, headers=headers)
print("Info recieved...")
return response
但是我想通過 SOAP 客戶端訪問服務。
這是他們在 PHP 中添加令牌的方式:
$soap->soapClient->_stream_context = stream_context_create([
'http' => [
'header' => sprintf('Authorization: Bearer %s', $authTokenResponse->token)
]
]);
關於如何將帶有令牌的標頭添加到 Python 中的客戶端請求的任何想法?
我在 SOF 中看到很多關於 SOAP+Python 的帖子,但無法解決問題。 即使有 Zeep 文檔,我也無法使其工作。
謝謝
我想做類似的事情,結果它在文檔中但它有點隱藏,你可以在這里找到它:
https://python-zeep.readthedocs.io/en/master/settings.html#context-manager
簡而言之,您可以執行以下操作:
import zeep
settings = zeep.Settings(extra_http_headers={'Authorization': 'Bearer ' + token})
client = zeep.Client(wsdl=url, settings=settings)
我不確定為什么接受的答案對我不起作用,但這就是我最終做的
import requests
from zeep import Client, Transport
headers = {
"Authorization": "Bearer " + get_token()
}
session = requests.Session()
session.headers.update(headers)
transport = Transport(session=session)
client = Client(wsdl=url, transport=transport)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.