【问题标题】:How to authenticate to Bluemix CF API using Python如何使用 Python 对 Bluemix CF API 进行身份验证
【发布时间】:2017-11-26 08:00:30
【问题描述】:

让我先说我可能忽略了一些简单的事情。

我正在尝试使用 Python 和 CF API 编写对我的 Bluemix 帐户的一些操作脚本。

首先到https://api.ng.bluemix.net/info获取authorization_endpoint,https://login.ng.bluemix.net/UAALoginServerWAR/

response = requests.get('https://api.ng.bluemix.net/info')

然后发布到 authorization_endpoint 以获取 oauth 令牌。

results = response.json()
auth_endpoint = results['authorization_endpoint'] + 'oauth/token?grant_type=password&client=cf'
http_payload = {
    'username': id,
    'password': pw,
    'client_id': 'cf'
    }
auth = ('cf', '')
response = requests.post(auth_endpoint, data=http_payload, auth=auth)

然后使用返回的 oauth 令牌调用 CF API,在本例中为 https://api.ng.bluemix.net/v2/organizations

results = response.json()
url = 'https://api.ng.bluemix.net/v2/organizations'
authorization = results['token_type'] + ' ' + results['access_token']
http_headers = {
    'accept': 'application/json',
    'content-type': 'application/json',
    'authorization': authorization
    }
response = requests.get(url, headers=http_headers)

但这会导致 404,{"description": "Unknown request", "error_code": "CF-NotFound", "code": 10000}。这是正确的方法吗?我忽略了什么?

【问题讨论】:

    标签: python api oauth ibm-cloud cloud-foundry


    【解决方案1】:

    这对我有用:

    id = 'changeme'
    pw = 'changeme'
    
    import json
    import urllib
    import requests
    
    response = requests.get('https://api.ng.bluemix.net/info')
    results = response.json()
    auth_endpoint = results['authorization_endpoint'] + '/oauth/token'
    
    data = 'grant_type=password&username={0}&password={1}'.format(id, pw)
    auth = ('cf', '')
    headers = {
        'accept': 'application/json',
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
    response = requests.post(auth_endpoint, data=data, headers=headers, auth=auth)
    
    results = response.json()
    url = 'https://api.ng.bluemix.net/v2/organizations'
    authorization = results['token_type'] + ' ' + results['access_token']
    http_headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'authorization': authorization
        }
    response = requests.get(url, headers=http_headers)
    
    print(response.text)
    

    返回:

    {
      "total_results": 6,
      "total_pages": 1,
      "prev_url": null,
      "next_url": null,
      "resources": [
      ...
    }
    

    【讨论】:

    • 谢谢,是的。这也适用于我。我在错误的地方寻找我的错误。我认为这与我生成令牌的方式有关。但是在我使用 curl 命令后,我意识到我的错误是一个简单而愚蠢的错字。我使用的 URL 是 https:\\api.ng.bluemix.net\V2\。在某些时候,我设法将“v”大写。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2023-03-11
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多