我目前有一个SurveyMonkey开发者草稿应用程序设置,并正在实施他们的documentation所描述的OAuth。我已经完成了第一步(将用户定向到SurveyMonkey的OAuth授权页面),但是一旦用户输入了他们的用户名和密码来授权SurveyMonkey访问,就像上面链接的第二步中指定的那样,我如何访问作为查询参数包含的短期代码?本质上,一旦我们离开了我正在构建的网站,我如何从用户正在查看的SurveyMonkey页面访问URL参数,但据我所知,我的网站无法立即访问?
发布于 2016-06-19 04:51:37
短暂的代码作为查询参数包含在您的redirect_uri中。在应用程序的设置页面中,您可以将标签为"OAuth重定向URL“的选项设置为指向您的服务器的链接。
假设你的网站是https://www.example.com,你的重定向URI可能类似于https://www.example.com/surveymonkey/oauth,你可以将其保存在你的应用程序的设置中。
因此,对于第1步,您将把用户发送到:
https://api.surveymonkey.net/oauth/authorize?response_type=code&redirect_uri=https://www.example.com/surveymonkey/oauth&client_id=<your_client_id>&api_key=<your_api_key>当用户在OAuth表单中单击"Authorize“时,我们将把短暂的代码作为查询参数发送给您的redirect_uri。因此,用户将被发送到:
https://www.example.com/surveymonkey/oauth?code=<short_lived_code>通常,您不会呈现页面(尽管您可以通过window.location.search或其他方式检查JavaScript中的代码),但是在主机的服务器端,您可以从GET参数中获取代码(取决于您的语言/框架),并在https://api.surveymonkey.net/oauth/token?api_key=<your_api_key>中将这个短暂的令牌交换为长期的访问令牌。
一个python示例:
import requests
def surveymonkey_oauth(request):
code = request.GET['code']
post_body = {
"client_secret": "your_client_secret",
"redirect_uri": "https://www.example.com/surveymonkey/oauth",
"grant_type": "authorization_code",
"code": code
}
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
response = requests.post("https://api.surveymonkey.net/oauth/token?api_key=<your_api_key>", headers=headers, data=post_body)
access_token = response['access_token']然后,您可以存储该访问令牌,并在希望为该用户向SurveyMonkey应用编程接口发出请求时为该用户获取该令牌。
我已经有一段时间没有使用node.js了,但是让我为您尝试一个节点示例,因为我看到您已经将express作为标记:
var http = require('http');
var querystring = require("querystring");
app.get('/surveymonkey/oauth', function (req, res) {
var code = req.query.code;
var post_body = querystring.stringify({
"client_secret": "your_client_secret",
"redirect_uri": "https://www.example.com/surveymonkey/oauth",
"grant_type": "authorization_code",
"code": code
});
var options = {
host: 'api.surveymonkey.net',
port: 443,
path: '/oauth/token?api_key=<your_api_key>',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_body)
}
}
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (body) {
// Get access_token from body and do what you like with it
});
});
req.write(post_body);
req.end();
});请注意,如果您只想访问自己的帐户,如果您向下滚动到应用程序的设置页面底部附近的凭据部分,则已经为您的帐户提供了访问令牌。
还要注意的是,处于“草稿”模式的应用程序只能访问您自己的帐户。
https://stackoverflow.com/questions/37899756
复制相似问题