为微软自定义应用获取认证令牌 实现Graph-API上传文件到Teams OneDrive
常见错误修正
grant_type使用客户端凭证流时固定取值为client_credentials,无需额外查找,但该流仅适用于服务端场景,绝对不能在前端代码中使用,client_secret暴露在前端会导致你的应用权限被任何人盗用。- 获取token的请求必须用
POST方法,不能用GET - 请求头
Content-Type必须设置为application/x-www-form-urlencoded,所有授权参数需要按表单格式拼接放在请求body中,不能放在requestOptions的根节点 - 你之前写的token请求地址有误,正确的格式是
https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token
本地临时测试方案(仅用于跑通流程,禁止上线)
如果只是本地测试功能,可以先用如下临时代码获取token,后续上线必须替换为Teams SSO方案:
// 注意:这段代码仅用于本地测试,绝对不要提交到代码仓库或者部署到公网 componentDidMount() { const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); // 表单格式拼接参数 const urlencoded = new URLSearchParams(); urlencoded.append("grant_type", "client_credentials"); urlencoded.append("client_id", "替换为你的client_id"); urlencoded.append("client_secret", "替换为你的client_secret"); urlencoded.append("scope", "https://graph.microsoft.com/.default"); const requestOptions = { method: 'POST', headers: myHeaders, body: urlencoded, redirect: 'follow' }; fetch("https://login.microsoftonline.com/替换为你的租户ID/oauth2/v2.0/token", requestOptions) .then(response => response.json()) .then(result => { console.log("拿到的token", result.access_token) // 拿到token后调用上传文件接口 uploadFile(result.access_token) }) .catch(error => console.log('获取token错误', error)); } // 上传文件方法 const uploadFile = (token) => { const myHeaders = new Headers(); myHeaders.append("Authorization", `Bearer ${token}`); myHeaders.append("Content-Type", "text/plain"); const raw = "测试上传内容"; const requestOptions = { method: 'PUT', headers: myHeaders, body: raw, redirect: 'follow' }; // 注意上传接口地址末尾要加/content才是正确的上传路径 fetch("https://graph.microsoft.com/v1.0/sites/OpenSesameTest/Shared%20Documents/General/FileB.txt:/content", requestOptions) .then(response => response.text()) .then(result => console.log("上传成功", result)) .catch(error => console.log('上传错误', error)); }
生产环境正确方案(Teams SSO)
你开发的是Teams Tab应用,应该使用Teams自带的SSO能力获取token,完全不需要在前端处理client_secret,步骤如下:
- 先在应用注册中配置Teams SSO相关的权限和公开API
- 用
microsoftTeams.authentication.getAuthToken()方法直接获取当前用户的token:
componentDidMount() { microsoftTeams.initialize(); microsoftTeams.authentication.getAuthToken({ successCallback: (token) => { console.log("SSO拿到的token", token); uploadFile(token); }, failureCallback: (error) => { console.log("SSO获取token失败", error); } }); }
内容的提问来源于stack exchange,提问作者7BitAscii
相关产品推荐
相关产品推荐

