嗨,我是Ruby/Rails的新手,我有一个关于如何使用GitHub的Octokit的Ruby版本来处理OAuth响应的问题。在阅读了这些文档之后,我对如何使用包装器和RestClient来遵循最佳实践感到有点困惑。当我授权我的应用程序时,响应返回一个“代码”,我应该用它来交换访问令牌。
在GitHub API文档中,它展示了一个使用Restclient的Sinatra示例,该示例目前在会话控制器的创建操作中。但是,它说在构建应用程序时应该采取不同的方法,并且应该使用Octokit库,但是我找不到任何关于如何将代码与Octokit交换为访问令牌的文档。
我的目标是能够通过用户的GitHub帐户为应用程序创建一个新成员,保存该信息,然后用该帐户登录,而不是创建用户名/密码。我在下面粘贴了我的new.html.erb代码,以显示我正在发出的请求。真的很感谢你的帮助,谢谢!
会话控制器
class SessionsController < ApplicationController
def new
@client_id = Octokit.client_id
end
def create
# CHANGE THIS TO USE OCTOKIT INSTEAD
session_code = request.env['rack.request.query_hash']['code']
result = RestClient.post('https://github.com/login/oauth/access_token',
{:client_id => Octokit.client_id,
:client_secret => Octokit.client_secret,
:code => session_code},
:accept => :json)
access_token = JSON.parse(result)['access_token']
end
endOAuth请求
<p>
Sign In with GitHub
</p>
<p>
<a href="https://github.com/login/oauth/authorize?scope=user:follow&client_id=<%= @client_id %>">Click here</a> to begin!</a>
</p>发布于 2014-01-26 17:38:59
因为它没有在自述中明确说明这一点。我建议的是总是通过源代码来更好地理解gem是如何工作的。您通常会发现,创业板的创建者已经编写了很好的代码,这是不言自明的,有时甚至评论,以提供更多的信息,如下所示。这里是您正在寻找的方法,祝您在学习Ruby/Rails和欢迎您的旅途中好运!如果你还有更多的问题,并遇到更多的问题,请告诉我。
# Retrieve the access_token.
#
# @param code [String] Authorization code generated by GitHub.
# @param app_id [String] Client Id we received when our application was registered with GitHub.
# @param app_secret [String] Client Secret we received when our application was registered with GitHub.
# @return [Sawyer::Resource] Hash holding the access token.
# @see http://developer.github.com/v3/oauth/#web-application-flow
# @example
# Octokit.exchange_code_for_token('aaaa', 'xxxx', 'yyyy', {:accept => 'application/json'})
def exchange_code_for_token(code, app_id = client_id, app_secret = client_secret, options = {})
options.merge!({
:code => code,
:client_id => app_id,
:client_secret => app_secret,
:headers => {
:content_type => 'application/json',
:accept => 'application/json'
}
})
post "#{web_endpoint}login/oauth/access_token", options
endhttps://stackoverflow.com/questions/21366656
复制相似问题