调用Azure API出现AuthenticationFailed错误,请求排查
React调用Azure API时AuthenticationFailed问题排查
环境与代码配置
核心调用代码
import { BrowserAuthError, PublicClientApplication } from '@azure/msal-browser'; import { MsalProvider, useMsal, AuthenticatedTemplate, UnauthenticatedTemplate } from '@azure/msal-react'; import { msalConfig } from './authConfig'; const pca = new PublicClientApplication(msalConfig); const { instance, accounts } = useMsal(); const loginRequest = { scopes: ["User.Read"], }; const response = await instance.acquireTokenPopup(loginRequest); const accessToken = response.accessToken; const fetchResponse = await fetch('https://management.azure.com/subscriptions/<subid>/resourceGroups/<rg>/providers/Microsoft.Network/frontDoors/<afd>?api-version=2021-06-01', { headers: { Authorization: `Bearer ${accessToken}`, }, }); const data = await fetchResponse.json();
authConfig配置
const msalConfig = { auth: { clientId: <clientId>, authority: `https://login.microsoftonline.com/<tenantId>`, redirectUri: window.location.origin, }, cache: { cacheLocation: "sessionStorage", storeAuthStateInCookie: false, }, };
当前状态与错误
已完成以下操作:
- 在应用中配置相关权限
- 创建服务主体并赋予订阅的Contributor权限
- 成功获取access token
调用Azure API时返回错误:
{ "error": { "code": "AuthenticationFailed", "message": "Authentication failed." } }
疑问
- 调用API失败遗漏了哪些步骤?
- 添加Azure Service Management API权限时要求管理员审批,附上权限及企业应用设置截图。
问题排查与解决步骤
1. 修正权限范围(核心问题)
当前请求token使用的["User.Read"]是Microsoft Graph的权限,无法用于Azure管理API。必须替换为Azure Service Management的专属范围:
const loginRequest = { scopes: ["https://management.azure.com/user_impersonation"], };
Azure资源管理器API仅认可包含https://management.azure.com/user_impersonation范围的token。
2. 确认管理员已完成权限审批
添加Azure Service Management API权限后,必须确保:
- 在Azure AD应用的API权限页面中,已添加
Azure Service Management的user_impersonation权限 - 租户管理员已点击授予管理员同意(未完成此步骤时,普通用户无法获取包含该权限的有效token)
3. 验证token有效性
获取token后,使用JWT解析工具检查以下字段:
aud字段必须为https://management.azure.comscp字段必须包含user_impersonation
若不符合,说明token无效,需重新请求。
4. 区分用户身份与服务主体权限
你创建的服务主体及Contributor权限是给应用身份使用的,而当前代码是通过用户登录获取token,需确保:
- 登录的用户本身拥有该订阅/资源组的Contributor权限(用户权限与服务主体权限相互独立)
- 若要使用服务主体身份调用API,需改用
ClientCredential认证流,而非当前的弹出登录流
5. 检查API路径与版本
确认资源路径中的<subid>、<rg>、<afd>已替换为实际有效值,同时验证API版本2021-06-01是否对应当前Front Door资源的支持版本。
内容的提问来源于stack exchange,提问作者Pradeep Vairamani
相关产品推荐
相关产品推荐

