JWT验证失败:受众'api://wrong-service'与预期的受众'api://my-service'不匹配
JWT validation failed: audience 'api://wrong-service' does not match expected audience 'api://my-service'
ID: security/oauth2-jwt-audience-mismatch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Spring Security 6.3.0 | active | — | — | — |
| MSAL.js 2.0.0 | active | — | — | — |
| PyJWT 2.9.0 | active | — | — | — |
| Auth0 SPA SDK 2.0.0 | active | — | — | — |
根因分析
JWT的'aud'(受众)声明与资源服务器配置的受众不匹配,通常是因为令牌是为不同的API签发的,或者客户端请求了错误的受众。
English
The JWT's 'aud' (audience) claim does not match the audience configured for the resource server, often because the token was issued for a different API or the client requested the wrong audience.
官方文档
https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3解决方案
-
更新资源服务器配置以期望正确的受众。例如,在Spring Boot中,设置`spring.security.oauth2.resourceserver.jwt.audiences=api://my-service`。
-
确保客户端应用程序在获取令牌时请求正确的受众。例如,在使用MSAL的Angular应用中,设置`extraQueryParameters: {audience: 'api://my-service'}`。 -
如果使用Azure AD,请验证API的应用程序ID URI,并确保客户端的API权限配置正确以请求该受众。
无效尝试
常见但无效的做法:
-
90% 失败
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.
-
100% 失败
Modifying the token's 'aud' claim client-side will fail signature validation, as the token is signed and any alteration invalidates the signature.
-
30% 失败
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.