【发布时间】:2020-02-05 02:53:17
【问题描述】:
我正在尝试使用此 python 脚本获取/创建 OAuth2 访问令牌:
import requests
import json
token_url = 'https://mytower.example.com/api/v2/tokens/'
data = {
"description": "My Access Token",
"application": 2,
"scope": "write"
}
client_id = "I457Uue7...Ikdiafhjd"
client_secret = "Xvcgsh8...Ikadfi84"
user = 'myaccount'
passwd = 'that works in the UI'
# Get token
params = {"grant_type": "password", "username": user, "password": passwd}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
response = requests.post(token_url, auth=(client_id, client_secret), headers=headers, params=params, verify=False)
print(f'{response.status_code} {response.content}')
if response.status_code == 200:
token = response.json()['access_token']
print(token)
当我运行脚本时出现此错误:
401 b'{"detail":"Authentication credentials were not provided. To establish a login session, visit /api/login/."}'
我已经查看了这里的文档:https://docs.ansible.com/ansible-tower/latest/html/administration/oauth2_token_auth.html,但我无法弄清楚。
请帮忙
更新:
当我执行这个 python 代码时:
import requests
import json
token_url = 'https://mytower.example.com/api/v2/tokens/'
headers = {"Content-Type": "application/json"}
user = 'me'
passwd = 'mypasswd'
# Get token
response = requests.post(token_url, verify=False, auth=(user, passwd))
print(f'{response.status_code} {response.content}')
token = response.json()['access_token']
print(token)
我得到这个输出:
401 b'{"detail":"Authentication credentials were not provided. To establish a login session, visit /api/login/."}'
更新二:
好的,这段代码得到了令牌:
import requests
token_url = 'https://mytower.example.com/api/v2/tokens/'
data = {
"description": "My Access Token",
"application": 2,
"scope": "write"
}
headers = { 'Content-Type': 'application/json' }
gen_user = 'me'
gen_pass = 'mypassword'
# Get token
response = requests.post(token_url, auth=(gen_user, gen_pass), headers=headers, json=data, verify=False)
print(f'{response.status_code} {response.content}')
【问题讨论】:
标签: ansible-tower