我目前正在尝试开发一个使用 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/