Karate API测试:Bearer令牌audience无效引发401认证失败
解决Azure AD令牌受众无效导致的API 401认证失败
问题原因
错误信息WWW-Authenticate: Bearer error="invalid_token", error_description="The audience <code>value</code> is invalid"明确说明:你生成的access token的受众(aud字段)与目标API要求的受众不匹配。
在客户端凭证(client_credentials)模式下,向Azure AD请求token时必须指定目标API的标识符,否则生成的token会默认以Azure AD的管理端点为受众,无法通过目标API的认证。
解决方案
1. 获取目标API的受众值
目标API的受众通常是其应用ID URI(比如https://your-company.com/your-api)或者API的客户端ID,可从Azure门户的API注册页面获取。
2. 修改Karate的token请求代码
根据你使用的Azure AD端点版本,添加对应的参数:
- 若使用v1端点(
oauth2/token):添加resource表单字段,值为目标API的受众。 - 若使用v2端点(
oauth2/v2.0/token):添加scope表单字段,值为{API受众}/.default(比如https://your-api-audience/.default)。
修改后的代码示例(以v1端点为例):
Given url `https://login.microsoftonline.com/tenant_id/oauth2/token` And form field grant_type = `client_credentials` And form field client_id = `your-client-id` And form field client_secret = `your-client-secret` And form field resource = `https://target-api-audience` // 替换为实际的目标API受众 When method post Then status 200 match response.access_token != null def access_token = response.access_token print access_token Given header Authorization = 'Bearer ' + access_token Given url 'your-target-api-url' And header accept = `plain/text` And header 'X-Mimic-User' = `confidential` When method GET Then status 200
3. 验证令牌受众
生成token后,可将其复制到jwt.io解码,检查aud字段的值是否与目标API要求的受众完全一致,确保没有拼写错误。
内容的提问来源于stack exchange,提问作者user8148927
相关产品推荐
相关产品推荐

