You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将OAuth令牌传入Locust请求时出现401错误求助

问题排查与修复

你的代码里有两个关键问题导致401错误:

1. Authorization头格式错误

'Bearer' + responseToken 里的Bearer和令牌之间缺少空格,服务器无法正确识别Bearer认证方案,应该写成 'Bearer ' + responseToken(注意Bearer后面的空格)。

2. Token请求的Content-Type头拼写错误

请求令牌时的头字段是 Content-Type,而不是 ContentType(缺少连字符),这会导致微软的token端点无法正确解析请求体,可能返回无效或错误的令牌。

额外优化建议

  • 用字典构建请求体,让requests自动处理URL编码,避免字符串拼接带来的特殊字符转义问题。
  • 添加token请求的错误检查,确保成功获取到access_token,避免后续请求因无有效令牌报错。

修正后的代码

from locust import HttpUser, constant, task
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class ProcessRequests(HttpUser):

    def on_start(self):
        tenant_id = "tenant123"
        client_id = "client123"
        secret = "secret123"
        scope = "api://123/.default"

        # 用字典构建请求体,自动处理编码
        body = {
            "grant_type": "client_credentials",
            "client_id": client_id,
            "client_secret": secret,
            "scope": scope
        }

        tokenResponse = self.client.post(
            f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token",
            data=body,  # 使用data参数传递字典,自动编码
            headers={"Content-Type": "application/x-www-form-urlencoded"}  # 修正头字段名
        )

        # 检查token请求是否成功
        tokenResponse.raise_for_status()
        
        response = tokenResponse.json()
        responseToken = response['access_token']
        
        # 修正Bearer和令牌之间的空格
        self.headers = {'Authorization': f'Bearer {responseToken}'}

    @task
    def get_labware(self):
        self.client.get("https://url/123", name="Labware", headers=self.headers)

    @task
    def get_instruments(self):
        self.client.get("https://url/456", name="Instruments", headers=self.headers)

关键修改说明:

  • 请求体改用字典+data参数传递,requests会自动完成URL编码,比字符串拼接更稳定可靠。
  • 修正Content-Type头的拼写,确保token端点能正确解析请求内容。
  • 给Authorization头的Bearer和令牌之间添加空格,符合OAuth2认证的格式规范。
  • 增加tokenResponse.raise_for_status(),如果token请求失败会直接抛出异常,便于快速定位问题。

内容的提问来源于stack exchange,提问作者JD2775

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:20:31