如何完成前端应用的三足授权?

How do I complete a 3-legged authorization from a front-end application?

我在设置连接到在我的前端设置的 Autodesk BIM360 的三足授权时遇到问题。后端 (localhost:8080) 有效,例如可以从 BIM360 访问和显示数据的简单界面,但我无法让前端 (localhost:3000) 工作。我能够获得 2-legged 授权来工作,但是由于 3-legged 需要登录,我不知道如何处理这个问题。

对于 2-legged OAuth(在前端)我使用了:

const getToken = async () => {
  const { data } = await axios.get(url_base + 'api/forge/oauth2lo/token');
  //console.log(data.access_token);
  return data.access_token;
};

但 3 条腿的设置更复杂。首先,设置一个 OAuth class:

class OAuth {
  constructor(session) {
    this._session = session;
  }

  getClient(scopes = config.scopes.internal) {
    const { client_id, client_secret, callback_url } = config.credentials;
    return new AuthClientThreeLegged(
      client_id,
      client_secret,
      callback_url,
      scopes
    );
  }
...

及相关路线:

...
router.get('/callback/oauth', async (req, res, next) => {
  console.log(req);
  const { code } = req.query;
  const oauth = new OAuth(req.session);
  try {
    await oauth.setCode(code);
    res.redirect('/');
  } catch (err) {
    next(err);
  }
});

router.get('/oauth/url', (req, res) => {
  const url =
    'https://developer.api.autodesk.com' +
    '/authentication/v1/authorize?response_type=code' +
    '&client_id=' +
    config.credentials.client_id +
    '&redirect_uri=' +
    config.credentials.callback_url +
    '&scope=' +
    config.scopes.internal.join(' ');
  res.end(url);
});
...

在前端,我尝试调用 '/oauth/url' 路径,它会将我带到登录屏幕,但登录会话仍保留在后端(在 localhost:8080 上)并且因此无法在前端访问BIM360数据。

我的问题是,如何在前端登录Autodesk账号,完成三足授权,才能在后台调用BIM360 API?

虽然使用 Authorization Code Grant on the server side, you can use an alternative, "Implicit Grant" 3-legged authentication from the client: https://forge.autodesk.com/en/docs/oauth/v2/tutorials/get-3-legged-token-implicit 处理三足认证更为常见。这样,在您的用户登录后,Autodesk 会将他们重定向到您的回调 URL,如下所示:

https://your.custom.app/callback#access_token=<token>&token_type=Bearer&expires_in=<seconds>

然后您的客户端 JavaScript 代码可以像这样提取访问代码:

   var params = {},
       queryString = location.hash.substring(1),
       regex = /([^&=]+)=([^&]*)/g,
       m;
   while (m = regex.exec(queryString)) {
     params[m[1]] = m[2];
   }
   alert("your access token is : " + params["access_token"]);