node.js - 带有访问 token 的 Oauth2 GET 请求在 NodeJS 中返回 403

标签 node.js oauth-2.0 access-token http-status-code-403 deviantart-api

我目前正在尝试开发一个使用 DeviantArt API 的 Node 应用程序。

所有请求都必须通过 Oauth2,因此我决定采用 client_credentials 流程,因为代码将全部私有(private)。

所以,一旦我在 DeviantArt 中注册了我的应用程序,我就得到了我的 clientId 和 clientSecret。

我使用client-oauth2包进行授权,代码如下所示:

const Oauth2 = require('client-oauth2');

...

function auth() {
  return new Promise((resolve, reject) => {
    let auth = new Oauth2({
      clientId: KEYS.client_id,
      clientSecret: KEYS.client_secret,
      accessTokenUri: AUTH_URL, // https://www.deviantart.com/oauth2/token
      authorizationGrants: ['credentials']
    });

    auth.credentials.getToken()
    .then((data) => {
      resolve({
        token: data.accessToken
      });
    })
    .catch(reject);
  });
}

到目前为止,这一切正常,我正在获取我的access_token。因此,我可以使用此 token 在 API 上执行任何请求,它实际上通过curl 和浏览器运行:

https://www.deviantart.com/api/v1/oauth2/browse/newest?access_token={{access_token}}

回到我的 Node 应用程序,我使用 request 包,代码如下所示:

const request= require('request');

...

function getDeviations(token) {
  return new Promise((resolve, reject) => {
    request(`https://www.deviantart.com/api/v1/oauth2/browse/newest?
        access_token=${token}`, (error, response, body) => {
      if (error || response.statusCode >= 400) {
        reject({
          error,
          response
        });
      } else {
        // do things and resolve
      }
    });
  });
}

它返回403 Forbidden

我花了两天时间用头撞键盘,寻找仅在使用 Node.js 时才返回 403 的原因。我寻找了来自浏览器、curl 和 node 的请求的差异,但没有任何线索......

有人知道可能发生什么吗?

最佳答案

我明白了...在 header 中伪造用户代理...

function getDeviations(token) {
  return new Promise((resolve, reject) => {
    request({
      url: `https://www.deviantart.com/api/v1/oauth2/browse/newest?
        access_token=${token}`,
      headers: {
        'User-Agent': 'curl/7.44.0'
      }
    }, (error, response, body) => {
      if (error || response.statusCode >= 400) {
        reject({
          error,
          response
        });
      } else {
        // do things and resolve
      }
    });
  });
}

我不敢相信这有效。

关于node.js - 带有访问 token 的 Oauth2 GET 请求在 NodeJS 中返回 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139746/

相关文章:

javascript - 如何在 node js v6 中将顺序函数转换为并行执行

mysql - NodeJS Sequelize : I can't update the primary key field's value

javascript - 如何在完成一个功能后调用不同的功能?

asp.net - 使用 JWT 进行模拟

node.js - Auth0/userinfo 端点返回未经授权的错误

javascript - 在 sails.js 中使用船长处理上传(进行中)

oauth-2.0 - Amplify/Cognito oauth 联合登录 (Google),不显示弹出窗口,而是在同一页面中重定向

javascript - Chrome 扩展程序 20 小时后没有 'Access-Control-Allow-Origin' header

shell - 如何通过curl获取GitHub OAuth2状态码来模拟Web Application Flow?

oauth-2.0 - 为什么刷新 token 被认为对于 SPA 来说是不安全的?