![](/img/trans.png)
[英]python social auth get access_token not work in Flask
[英]Auth0 obtain access_token for unit tests in Python
我試圖在Python中為我的燒瓶應用程序運行單元測試,以查找依賴於從access_token獲取的userID的路由。
有沒有一種方法可以在Python中調用auth0授權API,以獲得給定用戶名和密碼的用戶的access_token?
如果不是,那么調用授權API為其提供用戶名和密碼並獲得access_token的自動方法是什么?
最好是一個代碼段。
感謝@Jerdog,我構建了所需的代碼:
import json
import requests
# testing user password database:
testingUsers = {
'testingUser2@funnymail.com': 'BuQ3tUS3 :jbFAL',
'testingUser3w@funnymail.com': 'y(1726854(b(-KY'
}
def getUserToken(userName):
# client id and secret come from LogIn (Test Client)! which has password enabled under "Client > Advanced > Grant Types > Tick Password"
url = 'https://YOUR_AUTH0_DOMAIN/oauth/token'
headers = {'content-type': 'application/json'}
password = testingUsers[userName]
parameter = { "client_id":"Jfjrl12w55uqcJswWmMhSm5IG2Qov8w2e",
"client_secret": "3E5ZnqLFbPUppBLQiGDjB0H2GtXaLyaD26sdk2HmHrBXQaDYE453UCUoUHmt5nWWh",
"audience": 'AUTH0_AUDIENCE',
"grant_type": "password",
"username": userName,
"password": password, "scope": "openid" }
# do the equivalent of a CURL request from https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing
responseDICT = json.loads(requests.post(url, json=parameter, headers=headers).text)
return responseDICT['access_token']
@memoize # memoize code from: https://stackoverflow.com/a/815160
def getUserTokenHeaders(userName='testingUser2@funnymail.com'):
return { 'authorization': "Bearer " + getUserToken(userName)}
@memoize
裝飾器是為了避免在許多測試中多次調用以獲取令牌。 租戶必須為上述調用指定默認數據庫才能工作( 請參閱此答案 )。 關於數據庫名稱應該是什么( default_directory
)有點神秘,但是對我來說,只有Auth0用戶,數據庫是Username-Password-Authentication
,這似乎是新帳戶的默認名稱。
您是否看過https://auth0.com/docs/quickstart/backend/python/01-authorization演練? 完整的Python快速入門應該會為您提供一個良好的開端
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.