# JWT验证失败：受众'api://wrong-service'与预期的受众'api://my-service'不匹配

- **ID:** `security/oauth2-jwt-audience-mismatch`
- **领域:** security
- **类别:** auth_error
- **错误码:** `JWT_AUDIENCE_MISMATCH`
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

JWT的'aud'（受众）声明与资源服务器配置的受众不匹配，通常是因为令牌是为不同的API签发的，或者客户端请求了错误的受众。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Spring Security 6.3.0 | active | — | — |
| MSAL.js 2.0.0 | active | — | — |
| PyJWT 2.9.0 | active | — | — |
| Auth0 SPA SDK 2.0.0 | active | — | — |

## 解决方案

1. ```
   更新资源服务器配置以期望正确的受众。例如，在Spring Boot中，设置`spring.security.oauth2.resourceserver.jwt.audiences=api://my-service`。
   ```
2. ```
   确保客户端应用程序在获取令牌时请求正确的受众。例如，在使用MSAL的Angular应用中，设置`extraQueryParameters: {audience: 'api://my-service'}`。
   ```
3. ```
   如果使用Azure AD，请验证API的应用程序ID URI，并确保客户端的API权限配置正确以请求该受众。
   ```

## 无效尝试

- **** — Changing the expected audience in the resource server to accept any audience is insecure, as it would allow tokens meant for other services to access the API. (90% 失败率)
- **** — Modifying the token's 'aud' claim client-side will fail signature validation, as the token is signed and any alteration invalidates the signature. (100% 失败率)
- **** — Clearing the browser cache and retrying does not fix the issue because the token is generated by the identity provider and the audience mismatch is a configuration problem. (30% 失败率)
