【问题标题】:Auth0 obtain access_token for unit tests in PythonAuth0 获取 Python 中单元测试的 access_token
【发布时间】:2018-07-11 04:07:05
【问题描述】:

我正在尝试在 Python 中为我的烧瓶应用程序运行单元测试,以获得依赖于从 access_token 获得的用户 ID 的路由。

有没有办法在 Python 中调用 auth0 授权 API 来获取给定用户名和密码的用户的 access_token?

如果不是,那么调用授权 API 为其提供用户名和密码并获取 access_token 的自动化方式是什么?

最好有一个代码 sn-p。

【问题讨论】:

    标签: python unit-testing flask auth0


    【解决方案1】:

    您看过https://auth0.com/docs/quickstart/backend/python/01-authorization 演练吗? Python 的完整快速入门应该会给你一个好的开始

    【讨论】:

    【解决方案2】:

    感谢@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 装饰器是为了避免在多次测试中多次调用来获取令牌。租户必须为上述调用工作指定一个默认数据库 (see this answer)。数据库名称应该是什么(default_directory)有点神秘,但对我来说,只有 Auth0 用户,数据库是 Username-Password-Authentication,这似乎是新帐户的默认值。

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 2017-08-29
      • 1970-01-01
      • 2015-01-08
      • 2015-11-30
      • 2020-11-16
      • 2019-04-15
      相关资源
      最近更新 更多