OAuth报错:Tuple object is not callable及认证参数修改问题排查
问题:密码模式下请求Token报'Tuple object is not callable'错误
背景
原本基于client_credentials授权模式的代码可以正常运行:
f = open('creds.json') creds = json.load(f) def get_access_token(url, client_id, client_secret): response = requests.post( url, data={"grant_type": "client_credentials", "scope": "api://xyz.default"}, auth=(client_id, client_secret), ) return response.json()["access_token"] new_token = get_access_token(creds["auth_url"],client_id=creds["client_id"], client_secret=creds["client_secret"]) headers = {"loggedInUsername": "Test, User","Content-Type":"application/json",'Authorization': f"Bearer {new_token}"}
改为password授权模式后,Postman中参数配置可正常请求,但Python代码在pytest中抛出'Tuple object is not callable'错误:
def get_access_token(url, client_id, username, password): response = requests.post( url, data={"grant_type": "password", "scope": "api://xyz.default"}, auth=(client_id, username, password), ) return response.json()["access_token"] new_token = get_access_token(creds["auth_url"],client_id=creds["client_id"], username=creds["username"], password=creds["password"]) headers = {"loggedInUsername": "Test, User","Content-Type":"application/json",'Authorization': f"Bearer {new_token}"}
原因分析
错误确实是因为auth参数传了三元组导致的:
- requests库的
auth参数仅接受二元组(对应HTTP Basic Auth的用户名和密码),或者一个实现了__call__方法的认证对象。 - 当你传入三元组
(client_id, username, password)时,requests会尝试将这个元组当作可调用对象去执行,而元组本身没有可调用的方法,因此抛出'Tuple object is not callable'错误。 - 另外,OAuth2的
password授权模式并不需要用auth参数传递凭证,而是要把client_id、username、password都放在请求体的data参数中。
修正后的代码
f = open('creds.json') creds = json.load(f) def get_access_token(url, client_id, username, password): response = requests.post( url, data={ "grant_type": "password", "scope": "api://xyz.default", "client_id": client_id, "username": username, "password": password } ) return response.json()["access_token"] new_token = get_access_token( creds["auth_url"], client_id=creds["client_id"], username=creds["username"], password=creds["password"] ) headers = { "loggedInUsername": "Test, User", "Content-Type": "application/json", "Authorization": f"Bearer {new_token}" }
内容的提问来源于stack exchange,提问作者JD2775
相关产品推荐
相关产品推荐

