简体   繁体   中英

LinkedIn OAuth 2.0: undefined local variable or method `oauth' for #<LinkedinController:0x7d15970>

I've been using the gem LinkedIn OAuth 2.0. Right now I can get it to generate the linkedin signin page. However, the next thing that is supposed to happen is it sends to my callback link a code which I use to generate an access token. The problem is that the variable 'oauth' is generated in the authenticate action but then needs to be used again in the callback action. I've tried generating the oauth variable again using the exact same parameters, but when I do that I get an SSL certificate error. It seems like the exact same oauth instance needs to be used in both cases. Let me know if you have any thoughts. My code is below:

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

end

Getting an SSL certificate error doesn't mean that the instantiation is wrong. I don't know that gem, but I can't see why would that be a problem.

The require and the configuration block should not be inside the method (maybe you forgot the configuration from the second method?); the best place for those is in config/initializers/linkedin_oauth2.rb .

If you don't want to load it at startup, then you can put those in a private method oauth with memoization:

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

If the SSL error still occurs, you should investigate that. You can try creating a simple Ruby script with some example from the gem's readme, just to test the connection to LinkedIn.

Looks like the gem is using the faraday gem for HTTP, you can also try using that directly to make a simple call to LinkedIn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM