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

Angular 5调用Microsoft Graph OneNote API时遇401错误,令牌获取存疑

排查OneNote Graph API访问令牌问题(Angular 5隐式授权流)

看起来你在Angular 5里用隐式授权流获取Microsoft Graph令牌时遇到了困惑,不确定令牌是否正确获取,进而影响OneNote API的调用。我来帮你一步步排查:

1. 先确认令牌是否成功获取

隐式授权流成功后,令牌会附加在跳转回的URL哈希(#)部分,格式类似:

#access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6...&token_type=Bearer&expires_in=3599&scope=Notes.Read%20openid%20profile...

你可以在跳转回应用后,打开浏览器开发者工具的控制台,输入console.log(window.location.hash),看看输出里是否包含完整的access_token、token_type、scope等参数。

另外注意你代码里的URL拼接问题:你用了&作为参数分隔符,但在JavaScript字符串里应该直接用&,转义后的&会被当成参数名的一部分,导致授权请求参数解析错误。正确的拼接示例:

window.location.href = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?' + 
  'client_id=' + CLIENT_ID + 
  '&response_type=token' + 
  '&redirect_uri=' + encodeURIComponent(REDIRECT_URI) + 
  '&scope=' + encodeURIComponent('Notes.Read https://graph.microsoft.com/openid profile');

2. 验证令牌的有效性

拿到access_token后,你可以用微软的令牌解析工具来验证几个关键信息:

  • 受众(aud):必须是https://graph.microsoft.com,否则令牌无法用于Graph API调用
  • 权限(scp):必须包含OneNote相关权限,比如Notes.Read、Notes.ReadWrite,要和你申请的权限一致
  • 过期时间(exp):转换成UTC时间后,必须晚于当前时间,否则令牌已失效

3. Angular中正确处理令牌和API调用

隐式流跳转回来后,Angular的路由可能会处理哈希,所以你需要手动解析哈希参数,比如写个工具函数:

parseAuthHash(): { access_token?: string; token_type?: string; expires_in?: string } {
  const hash = window.location.hash.slice(1);
  return hash.split('&').reduce((acc, curr) => {
    const [key, value] = curr.split('=');
    acc[key] = decodeURIComponent(value);
    return acc;
  }, {} as any);
}

调用OneNote API时,一定要在请求头里带上Bearer令牌:

import { HttpClient, HttpHeaders } from '@angular/common/http';

constructor(private http: HttpClient) {}

fetchOneNoteNotebooks(accessToken: string) {
  const headers = new HttpHeaders({
    'Authorization': `Bearer ${accessToken}`
  });
  return this.http.get('https://graph.microsoft.com/v1.0/me/onenote/notebooks', { headers });
}

4. 检查Azure AD应用配置

最后别忘了确认你的Azure AD应用设置是否正确:

  • 隐式授权流是否开启:在应用的“认证”设置里,勾选“访问令牌”和“ID令牌”(如果需要)
  • 重定向URI是否完全匹配:要和你代码里的redirect_uri一致,包括协议(http/https)、端口、路径
  • 权限是否已添加并授予:在“API权限”里添加Microsoft Graph的OneNote权限,并且管理员已授予(如果是租户内应用)

内容的提问来源于stack exchange,提问作者Sia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:28:36