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

浏览器中Fetch获取Microsoft Bearer Token失败问题求助

问题核心与解决方案

客户端凭证(client_credentials)模式完全不适合在浏览器环境中使用——你的client_secret会直接暴露给所有访问页面的用户,这属于严重的安全漏洞,微软的OAuth2服务也会拒绝来自浏览器的这类请求,这就是你在浏览器里调用失败的根本原因。

Node.js和Postman能正常工作,是因为它们属于服务端/本地工具环境,不会把敏感的client_secret暴露出去。

你需要做的调整

1. 立即移除浏览器代码中的敏感内容

  • 删除client_secret参数:浏览器环境下绝对不能出现这个敏感密钥
  • 删除Cookie头:Postman的Cookie是它自身的会话数据,浏览器请求不需要携带,反而可能引发跨域相关问题

2. 正确的实现流程

把获取Token和调用Graph API的逻辑移到你的后端服务(比如你已经能用的Node.js服务)中:

  • 后端新增一个接口(比如/api/get-graph-data),在接口内部用客户端凭证模式请求微软的Token,再用Token调用Graph API获取数据
  • 浏览器前端只需调用你自己的后端接口,直接拿到最终业务数据(不建议直接返回Token给前端,避免额外的安全风险)

示例代码

后端(Node.js/Express)示例

const express = require('express');
const fetch = require('node-fetch');
const app = express();

app.get('/api/get-graph-data', async (req, res) => {
  try {
    // 1. 获取微软Graph Token
    const tokenResponse = await fetch('https://login.microsoftonline.com/你的租户ID/oauth2/v2.0/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        client_id: '你的客户端ID',
        scope: 'https://graph.microsoft.com/.default',
        client_secret: '你的客户端密钥',
        grant_type: 'client_credentials'
      })
    });
    const tokenData = await tokenResponse.json();

    // 2. 使用Token调用Graph API(示例:获取用户信息)
    const graphResponse = await fetch('https://graph.microsoft.com/v1.0/users', {
      headers: {
        'Authorization': `Bearer ${tokenData.access_token}`
      }
    });
    const graphData = await graphResponse.json();

    res.json(graphData);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => console.log('后端服务运行在3000端口'));

浏览器前端示例

fetch('http://localhost:3000/api/get-graph-data')
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:15:54