获取Malwarebytes API访问令牌后仍遇未授权错误,请求技术协助
Malwarebytes API 未授权问题修复
你的代码核心问题是请求头里的Authorization字段没有正确使用实际的access token,导致API识别不到有效授权。
错误分析
- 构建headers时,你把变量
token_response当成字符串字面量写死了:
API收到的令牌是字符串'Authorization':'Bearer token_response',token_response,而非你实际获取到的令牌值。 - 获取token时用
[0]作为默认值不合适,换成空字符串或None更便于后续排查问题。
修正后的代码
from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import BackendApplicationClient import requests import json CLIENT_ID = "你的Client ID" CLIENT_SECRET = "你的Client Secret" grant_type = 'client_credentials' body_params = {'grant_type': grant_type} # 获取access token token_url = 'https://api.malwarebytes.com/oneview/oauth2/token' response = requests.post(token_url, data=body_params, auth=(CLIENT_ID, CLIENT_SECRET)) response.raise_for_status() # 获取token失败时直接抛出异常,快速定位问题 response_token = response.json() token_response = response_token.get("access_token", "") # 修正默认值为空字符串 # 检查token是否有效 if not token_response: print("获取access token失败") exit() # 正确构建授权请求头 headers = { 'Authorization': f'Bearer {token_response}', # 用f-string插入实际token值 'Content-Type': 'application/x-www-form-urlencoded' } # 请求站点数据 sites_response = requests.get('https://api.malwarebytes.com/oneview/v1/sites', headers=headers) print(sites_response.text) print(sites_response.status_code)
额外优化说明
response.raise_for_status():获取token阶段如果请求失败(比如Client ID/Secret错误),直接终止流程并抛出异常,避免后续无效请求。- token有效性检查:提前判断是否拿到有效token,减少不必要的API调用。
内容的提问来源于stack exchange,提问作者cookiecrumbs12
相关产品推荐
相关产品推荐

