2016-06-18 43 views
0

我目前有一个SurveyMonkey开发人员草稿应用程序正在建立并正在实施OAuth,如其documentation所述。我已经完成了第1步(将用户直接指向SurveyMonkey的OAuth授权页面),但是一旦用户输入用户名和密码授权SurveyMonkey访问权限(如上面链接的步骤2中所述),我如何才能访问短期代码作为查询参数?实质上,一旦我们离开了我正在构建的网站,我如何从用户正在查看的SurveyMonkey页面访问URL参数,但据我所知,我的网站没有立即访问权限?为SurveyMonkey实施OAuth,步骤2

回答

0

短期代码作为查询参数包含在您的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形式的“授权”,我们将在短暂的代码发送到您的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>上交换该短期令牌以获得长期访问令牌。

蟒蛇例如:

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 API为用户的请求获取它的用户。

我没有用Node.js的在一段时间,但让我尝试为您节点的例子,因为我看你有明确的标签:

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

请注意,如果你只是想访问自己的帐户,如果您在Credentials部分的应用程序的“设置”页面底部附近向下滚动,则已为您自己的帐户提供访问令牌。

另请注意,“草稿”模式下的应用程序只能访问您自己的帐户。

+0

我尽可能忠实地修改了你的代码,并陷入了困境,正如这个问题所描述的:http://stackoverflow.com/questions/38155717/how-to-access-params-from-url-after-redirect-to - 不同站点快车 –