python - Auth0获取access_token用于Python中的单元测试

标签 python unit-testing flask auth0

我正在尝试在 Python 中为我的 Flask 应用程序运行单元测试,以获取依赖于从 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 装饰器是为了避免在多次测试中多次调用来获取 token 。租户必须为上述调用指定一个默认数据库才能工作 ( see this answer )。数据库名称应该是什么(default_directory)有点神秘,但对我来说,只有 Auth0 用户,数据库是用户名-密码-身份验证 >,这似乎是新帐户的默认设置。

关于python - Auth0获取access_token用于Python中的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48552474/

相关文章:

Javascript:使用 Sinon 模拟构造函数

c# - DbSet 模拟,第二次调用 ToList 时没有结果

python - 如何检查 pymodbus 版本以解码 float_32 值?

python - 如何使用 PyQt 通知 Python 进程正在退出?

java - Spring Rest 文档不处理 html 标签

python - flask 模板 : nginx cache or serve static assets called in jinja markups

HTML 中的 PHP 无法使用 Flask 工作

python - 如何在 jinja2 中获取 WTForms 验证器

python - Python dict 是一个对象吗?

python - 使用 freeglut 为 Python 3.5.2 设置 PyOpenGL