【问题标题】:LinkedIn OAuth 2.0: undefined local variable or method `oauth' for #<LinkedinController:0x7d15970>LinkedIn OAuth 2.0:#<LinkedinController:0x7d15970> 的未定义局部变量或方法“oauth”
【发布时间】:2016-06-11 18:01:58
【问题描述】:

我一直在使用 gem LinkedIn OAuth 2.0。现在我可以让它生成linkedin登录页面。但是,接下来应该发生的事情是它向我的回调链接发送一个代码,我用它来生成访问令牌。问题是变量 'oauth' 是在身份验证操作中生成的,但随后需要在回调操作中再次使用。我尝试使用完全相同的参数再次生成 oauth 变量,但是当我这样做时,我得到了 SSL 证书错误。似乎在这两种情况下都需要使用完全相同的 oauth 实例。如果您有任何想法,请告诉我。我的代码如下:

def authenticate

    require "linkedin-oauth2"


    LinkedIn.configure do |config|
      config.client_id     = "Mycode"
      config.client_secret = "Mysecret"

      # This must exactly match the redirect URI you set on your application's
      # settings page. If your redirect_uri is dynamic, pass it into
      # `auth_code_url` instead.
      config.redirect_uri  = "http://localhost:3000/auth/linkedin/callback"
    end


    oauth = LinkedIn::OAuth2.new()


    url = oauth.auth_code_url

    redirect_to url

end


def callback

    require "linkedin-oauth2"



    code = params[:code]

    access_token = oauth.get_access_token(code)

    api = LinkedIn::API.new(access_token)

    my_job_titles = api.profile(fields: ["id", {"positions" => ["title"]}])

    puts my_job_titles

    redirect_to("/")

end

结束

【问题讨论】:

    标签: ruby-on-rails oauth-2.0 linkedin-api


    【解决方案1】:

    收到 SSL 证书错误并不意味着实例化错误。我不知道那个宝石,但我不明白为什么会有问题。

    requireconfiguration 块不应该在方法内部(也许你忘记了第二种方法的配置?);最好的地方是config/initializers/linkedin_oauth2.rb

    如果你不想在启动时加载它,那么你可以将它们放在一个私有方法oauth 中,并带有记忆:

    def oauth
      @oauth ||=
        begin
          require "linkedin-oauth2"
          LinkedIn.configure do |config|
            ...
          end
          LinkedIn::OAuth2.new()
        end
    end
    

    如果 SSL 错误仍然存​​在,您应该对此进行调查。您可以尝试使用 gem 的自述文件中的一些示例创建一个简单的 Ruby 脚本,以测试与 LinkedIn 的连接。

    看起来 gem 是 using faraday gem 用于 HTTP,您也可以尝试直接使用它来简单地调用 LinkedIn。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-26
      • 2020-03-29
      • 2018-04-19
      • 2015-01-01
      • 2013-12-17
      相关资源
      最近更新 更多