如何使用Node.js更简便生成Autodesk Forge three-legged token
Node.js 生成Autodesk Forge Three-legged Token最简方案
Three-legged OAuth 流程需用户手动授权,无法完全离线生成,以下为仅依赖基础模块的精简实现,无需搭建完整Web服务:
依赖准备
仅需安装axios用于发送请求,无其他重型依赖:npm install axios
最简实现代码
const axios = require('axios'); const readline = require('readline'); const { URL } = require('url'); // 替换为自己的Forge应用对应参数 const FORGE_CLIENT_ID = '你的客户端ID'; const FORGE_CLIENT_SECRET = '你的客户端密钥'; const FORGE_CALLBACK_URL = '你的应用回调地址'; const FORGE_SCOPE = 'data:read data:write'; // 可根据实际业务调整权限范围 // 生成用户授权链接 const authUrl = new URL('https://developer.api.autodesk.com/authentication/v2/authorize'); authUrl.searchParams.set('response_type', 'code'); authUrl.searchParams.set('client_id', FORGE_CLIENT_ID); authUrl.searchParams.set('redirect_uri', FORGE_CALLBACK_URL); authUrl.searchParams.set('scope', FORGE_SCOPE); console.log('请访问以下链接完成授权:', authUrl.toString()); // 读取用户输入的授权返回code const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('请输入授权后页面地址中的code参数值:', async (code) => { try { // 用授权code兑换token const res = await axios.post('https://developer.api.autodesk.com/authentication/v2/token', new URLSearchParams({ grant_type: 'authorization_code', client_id: FORGE_CLIENT_ID, client_secret: FORGE_CLIENT_SECRET, code: code, redirect_uri: FORGE_CALLBACK_URL }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ); console.log('获取到的Three-legged Token:', res.data.access_token); console.log('Token有效期:', res.data.expires_in, '秒'); console.log('刷新Token:', res.data.refresh_token); } catch (err) { console.error('获取Token失败:', err.response?.data || err.message); } rl.close(); });
操作步骤
- 替换代码中所有占位的应用参数后直接运行脚本
- 访问控制台输出的授权链接,登录Autodesk账号完成授权
- 复制授权后跳转页面地址中的
code参数值,粘贴到控制台回车即可直接获取token - 后续可保存返回的
refresh_token,无需重复授权,仅需将请求中grant_type替换为refresh_token即可直接刷新获取新的访问token
内容的提问来源于stack exchange,提问作者John Kuldeep Roshan Kerketta
相关产品推荐
相关产品推荐

