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

使用Active Directory令牌从Angular调用Web API返回401错误如何处理?

问题原因及解决方案

1. Access Token Scope配置错误

这是最常见的401触发原因:你当前获取的令牌没有指定目标Web API的自定义scope,默认获取的令牌受众是微软Graph服务而非你的自建Web API,自然无法通过API的身份校验。
你需要在调用loginRedirect或者主动获取令牌时,传入你Web API暴露的scope,示例如下:

// 登录时指定scope,替换为你自己Web API注册时暴露的scope,格式一般为 api://{API客户端ID}/{scope名}
loginRedirect(){
 this.msalServices.loginRedirect({
   scopes: ["api://xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Access.Api"]
 });
}

你也可以在调用API前主动拉取最新令牌,避免本地缓存的令牌过期:

async testAPI1(){
  // 主动获取最新令牌,不要依赖本地存储的this.token
  const account = this.msalServices.instance.getActiveAccount();
  if (!account) return;
  const tokenRes = await this.msalServices.instance.acquireTokenSilent({
    scopes: ["api://xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/Access.Api"],
    account: account
  });
  const myheaders = new HttpHeaders({
      'Content-Type': 'application/json; charset=utf-8',
      'Authorization': `Bearer ${tokenRes.accessToken}`
  });
  console.log("calling Web APIs App 'GetSecureMessage' API ...");
  this.http.get('https://localhost:44362/v2/Site/GetSecureMessage', {headers: myheaders})
  .subscribe((data)=>{
      console.warn(data);
  })
}

2. 本地存储令牌失效

你把令牌存在组件的this.token变量里,令牌有效期一般只有1小时,过期后或者页面刷新后本地变量值会丢失/失效,调用API时传的就是无效令牌。每次调用API前都通过acquireTokenSilent拉取最新令牌即可解决。

3. Web API校验配置错误

如果确认scope配置正确,可以把拿到的令牌解析后检查以下字段是否和你API端的配置匹配:

  • aud字段必须等于你Web API的应用ID URI或者客户端ID
  • iss字段必须和你API端Azure AD校验配置的颁发地址一致
  • 你的Web API必须在Azure AD中配置了正确的授权策略,允许你的Angular客户端应用访问

多余配置清理

你请求头里的Access-Control-Allow-Origin是服务端返回的响应头,客户端请求里加这个完全没有作用,可以直接删除。

内容的提问来源于stack exchange,提问作者K.Z

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:09:05