一般来说,我对Rails web开发和编码还比较陌生。我目前正在开发一个web应用程序,它应该从我的Fitbit帐户中检索数据。这是通过Fibit API和OAuth2.0完成的。
本质上,这是我的问题。如Fitbit教程网站https://dev.fitbit.com/apps/oauthinteractivetutorial所示,我需要从Fitbit用户那里获得授权。我尝试使用以下正确的URL来完成此操作
<%= link_to "Sign in with Fitbit", "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=228BT5&redirect_uri=http%3A%2F%2Fwww.builtbyburton.com%2Foauth2%2Fcallback&scope=activity%20location%20profile%20sleep&expires_in=604800" %>当调用它时,用户将按预期重定向到以下URL:
http://www.builtbyburton.com/oauth2/callback?code=1093d4dc25f0c61acbbf8128a9247b0efd448c35#_=_目前,我需要捕获从code=到#_=_的URL段,然后需要解析这个片段。我尝试使用嵌入的卷发来完成它,如下所示:
<pre class="embedcurl">curl -X POST -i -H 'Authorization: Basic MjI4QlQ1OmU4OWFkZWJmYTUzNTU1MGMyNGUyNjdhOWRjM2MxNzIy' -H 'Content-Type: application/x-www-form-urlencoded' -d "clientId=228BT5" -d "grant_type=authorization_code" -d "redirect_uri=http%3A%2F%2Fwww.builtbyburton.com%2Foauth2%2Fcallback" -d "code=1093d4dc25f0c61acbbf8128a9247b0efd448c35" https://api.fitbit.com/oauth2/token</pre>在那里,我需要解析响应,这将允许我提出请求。总的来说,我只是不确定如何从授权链接获取到使用OAuth2.0访问令牌发出请求。谢谢你的帮助!
发布于 2017-06-01 05:17:21
根据菲比特博士
Fitbit使用OAuth 2.0进行用户授权和API身份验证。当Fitbit用户授权您的应用程序访问其数据时,OAuth 2.0框架要求您的应用程序获得访问令牌。访问令牌用于向Fitbit API发出HTTP请求。 您不需要使用Fitbit特定的库来使用Fitbit Web API。相反,我们建议您使用为平台提供的最佳OAuth 2.0或HTTP库。如果您还没有最喜欢的HTTP2.0或OAuth库,我们在这里列出了一些
红宝石没有列出任何列表,但如果你谷歌rails oauth2,第一个成功的例子是:
https://github.com/intridea/oauth2
这里的例子看起来很简单:
gem install oauth2rails相当于将以下内容添加到Gemfile中:
gem oauth2下面是示例代码:
client = OAuth2::Client.new('client_id', 'client_secret', :site => 'https://example.org')
client.auth_code.authorize_url(:redirect_uri => 'http://localhost:8080/oauth2/callback')
# => "https://example.org/oauth/authorization?response_type=code&client_id=client_id&redirect_uri=http://localhost:8080/oauth2/callback"
token = client.auth_code.get_token('authorization_code_value', :redirect_uri => 'http://localhost:8080/oauth2/callback', :headers => {'Authorization' => 'Basic some_password'})
response = token.get('/api/resource', :params => { 'query_foo' => 'bar' })
response.class.name
# => OAuth2::Response原来的答案:
我尝试使用嵌入的卷发来完成它,如下所示:
在html文件中不能有任意代码。Rails使用所谓的ERB (或您选择的另一个解析引擎)来解析位于rails项目中特定目录中的页面,比如page1.html.erb --但是您必须遵循ERB解析的规则。您可以让ERB执行任意的ruby代码,但是bash命令,比如curl甚至不是ruby代码--它是bash代码。
_ 目前,我需要捕获代码=到#_=_的URL段
url的这一部分称为查询字符串。你可以这样做:
require 'uri'
url = 'http://www.builtbyburton.com/oauth2/callback?code=1093d4dc25f0c61acbbf8128a9247b0efd448c35#_=_'
obj = URI(url)
query_str = obj.query
puts query_str
--output:--
code=1093d4dc25f0c61acbbf8128a9247b0efd448c35您可以获得这样的授权代码:
name, value = query_str.split '='
puts value
--output:--
1093d4dc25f0c61acbbf8128a9247b0efd448c35https://stackoverflow.com/questions/44297924
复制相似问题