如何使用Python对Bluemix CF API进行身份验证

时间:2017-06-22 21:20:35

标签: python api oauth ibm-cloud cloudfoundry

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

我试图用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,{"描述":"未知请求"," error_code":" CF-NotFound", "代码":10000}。这是正确的方法吗?我在俯瞰什么?

1 个答案:

答案 0 :(得分: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": [
  ...
}