繁体   English   中英

具有访问令牌的Oauth2 GET请求在NodeJS中返回403

[英]Oauth2 GET request with access token returns 403 in NodeJS

我目前正在尝试开发使用DeviantArt API的节点应用程序。

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

因此,一旦我在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 因此,我可以使用此令牌在API上执行任何请求,并且它实际上可以通过curl和浏览器使用:

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

回到我的节点应用程序中,我正在使用请求包,代码如下所示:

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才能返回403的原因。 我一直在寻找来自浏览器,curl和node的请求中的差异,但一点都不知道...

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

我明白了...伪造标题中的用户代理...

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
      }
    });
  });
}

我不敢相信这行得通。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM