Sorcery/sorcery

Can't solve Oauth2 error

Closed this issue · 11 comments

Configuration

  • Sorcery Version: ~> 0.16.3
  • Ruby Version: 2.6.10
  • Framework: Rails 6.0.4.8
  • Platform: Mac

Expected Behavior

I used sorcery gem (version 11.0), but updated Rails version from 5.2 to 6.0.4.8, then the below error happened for Facebook login..

undefined method encode for <Hash ~>

Above error happens at Oauth2 client.rb file, especially 'response' method from Sorcery client.rb below lines.

          def sorcery_fetch_user_hash(provider_name)
            # the application should never ask for user hashes from two different providers
            # on the same request.  But if they do, we should be ready: on the second request,
            # clear out the instance variables if the provider is different
            provider = sorcery_get_provider provider_name
            if @provider.nil? || @provider != provider
              @provider = provider
              @access_token = nil
              @user_hash = nil
            end

            # delegate to the provider for the access token and the user hash.
            # cache them in instance variables.
            @access_token ||= @provider.process_callback(params, session) # sends request to oauth agent to get the token
   → this is the problem code.
            @user_hash ||= @provider.get_user_hash(@access_token) # uses the token to send another request to the oauth agent requesting user info
            nil
          end

Could you let me know if there are same issues when updating Rails updates...

I need to solve this problem urgently because of our products is still running...

Rails 6 should be compatible, although Facebook has been known to make breaking API changes with their OAuth in the past.

If you're using Sorcery v0.11, please update to v0.16.3 and try again. There are security and compatibility updates that have been included since v0.11.

@joshbuker

Thank you for replying.
Sorry my mis communication. Actually I just updated Rails Rails 6.0.4.8 and Sorcery v0.16.3 together.
Then above errors happens except for twitter login..

Could you kindly check below my sorcery files ??

config/initializers/sorcery.rb

# The first thing you need to configure is which modules you need in your app.
# The default is nothing which will include only core features (password encryption, login/logout).
# Available submodules are: :user_activation, :http_basic_auth, :remember_me,
# :reset_password, :session_timeout, :brute_force_protection, :activity_logging, :external
Rails.application.config.sorcery.submodules = [:core, :remember_me, :user_activation, :external, :reset_password, :session_timeout]

# Here you can configure each submodule's features.
Rails.application.config.sorcery.configure do |config|
  # -- core --
  # What controller action to call for non-authenticated users. You can also
  # override the 'not_authenticated' method of course.
  # Default: `:not_authenticated`
  #
  # config.not_authenticated_action =


  # When a non logged in user tries to enter a page that requires login, save
  # the URL he wanted to reach, and send him there after login, using 'redirect_back_or_to'.
  # Default: `true`
  #
  # config.save_return_to_url =


  # Set domain option for cookies; Useful for remember_me submodule.
  # Default: `nil`
  #
  # config.cookie_domain =


  # Allow the remember_me cookie to be set through AJAX
  # Default: `true`
  #
  # config.remember_me_httponly =


  # -- session timeout --
  # How long in seconds to keep the session alive.
  # Default: `3600`
  #
  config.session_timeout = 1.month


  # Use the last action as the beginning of session timeout.
  # Default: `false`
  #
  # config.session_timeout_from_last_action =


  # -- http_basic_auth --
  # What realm to display for which controller name. For example {"My App" => "Application"}
  # Default: `{"application" => "Application"}`
  #
  # config.controller_to_realm_map =


  # -- activity logging --
  # will register the time of last user login, every login.
  # Default: `true`
  #
  # config.register_login_time =


  # will register the time of last user logout, every logout.
  # Default: `true`
  #
  # config.register_logout_time =


  # will register the time of last user action, every action.
  # Default: `true`
  #
  # config.register_last_activity_time =


  # -- external --
  # What providers are supported by this app, i.e. [:twitter, :facebook, :github, :linkedin, :xing, :google, :liveid, :salesforce] .
  # Default: `[]`
  #
  config.external_providers = [:twitter, :facebook, :apple]


  # You can change it by your local ca_file. i.e. '/etc/pki/tls/certs/ca-bundle.crt'
  # Path to ca_file. By default use a internal ca-bundle.crt.
  # Default: `'path/to/ca_file'`
  #
  # config.ca_file =


  # For information about LinkedIn API:
  # - user info fields go to https://developer.linkedin.com/documents/profile-fields
  # - access permissions go to https://developer.linkedin.com/documents/authentication#granting
  #
  # config.linkedin.key = ""
  # config.linkedin.secret = ""
  # config.linkedin.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=linkedin"
  # config.linkedin.user_info_fields = ['first-name', 'last-name']
  # config.linkedin.user_info_mapping = {first_name: "firstName", last_name: "lastName"}
  # config.linkedin.access_permissions = ['r_basicprofile']
  #
  #
  # For information about XING API:
  # - user info fields go to https://dev.xing.com/docs/get/users/me
  #
  # config.xing.key = ""
  # config.xing.secret = ""
  # config.xing.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=xing"
  # config.xing.user_info_mapping = {first_name: "first_name", last_name: "last_name"}
  #
  #
  # Twitter will not accept any requests nor redirect uri containing localhost,
  # make sure you use 0.0.0.0:3000 to access your app in development
  #
  config.twitter.key = ENV['TWITTER_API_KEY'] || Settings.dig(:twitter, :api_key)
  config.twitter.secret = ENV['TWITTER_API_SECRET'] || Settings.dig(:twitter, :api_secret)
  config.twitter.callback_url = ENV['TWITTER_CALLBACK_URL'] || Settings.dig(:twitter, :callback_url)
  config.twitter.user_info_mapping = {:email => "email"}
  # メールアドレス取得できるように
  config.twitter.user_info_path = '/1.1/account/verify_credentials.json?include_email=true'

  config.facebook.key = ENV['FACEBOOK_API_KEY'] || Settings.dig(:facebook, :api_key)
  config.facebook.secret = ENV['FACEBOOK_API_SECRET'] || Settings.dig(:facebook, :api_secret)
  config.facebook.callback_url = ENV['FACEBOOK_CALLBACK_URL'] || Settings.dig(:facebook, :callback_url)
  config.facebook.user_info_mapping = {:email => "email"}
  config.facebook.user_info_path = "me?fields=email,first_name,last_name"
  config.facebook.access_permissions = ["email"]
  config.facebook.scope = "email"
  config.facebook.display = "page"
  config.facebook.api_version = "v2.8"
  config.facebook.instance_variable_set "@parse", :json

  config.apple.key = Settings.dig(:apple, :api_key_from_rtf)
  config.apple.callback_url = Settings.dig(:apple, :callback_url)
  config.apple.key_id = Settings.dig(:apple, :key_id)
  config.apple.team_id = Settings.dig(:apple, :team_id)
  config.apple.auth_key = Settings.dig(:apple, :auth_key)
  config.apple.user_info_mapping = { email: 'email' }
  #
  # config.github.key = ""
  # config.github.secret = ""
  # config.github.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=github"
  # config.github.user_info_mapping = {:email => "name"}
  #
  # config.google.key = ""
  # config.google.secret = ""
  # config.google.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=google"
  # config.google.user_info_mapping = {:email => "email", :username => "name"}
  #
  # config.vk.key = ""
  # config.vk.secret = ""
  # config.vk.callback_url = "http://0.0.0.0:3000/oauth/callback?provider=vk"
  # config.vk.user_info_mapping = {:login => "domain", :name => "full_name"}
  #
  # To use liveid in development mode you have to replace mydomain.com with
  # a valid domain even in development. To use a valid domain in development
  # simply add your domain in your /etc/hosts file in front of 127.0.0.1
  #
  # config.liveid.key = ""
  # config.liveid.secret = ""
  # config.liveid.callback_url = "http://mydomain.com:3000/oauth/callback?provider=liveid"
  # config.liveid.user_info_mapping = {:username => "name"}

  # For information about JIRA API:
  # https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+OAuth+authentication
  # to obtain the consumer key and the public key you can use the jira-ruby gem https://github.com/sumoheavy/jira-ruby
  # or run openssl req -x509 -nodes -newkey rsa:1024 -sha1 -keyout rsakey.pem -out rsacert.pem to obtain the public key
  # Make sure you have configured the application link properly

  # config.jira.key = "1234567"
  # config.jira.secret = "jiraTest"
  # config.jira.site = "http://localhost:2990/jira/plugins/servlet/oauth"
  # config.jira.signature_method =  "RSA-SHA1"
  # config.jira.private_key_file = "rsakey.pem"

  # For information about Salesforce API:
  # https://developer.salesforce.com/signup &
  # https://www.salesforce.com/us/developer/docs/api_rest/
  # Salesforce callback_url must be https. You can run the following to generate self-signed ssl cert
  # openssl req -new -newkey rsa:2048 -sha1 -days 365 -nodes -x509 -keyout server.key -out server.crt
  # Make sure you have configured the application link properly
  # config.salesforce.key = '123123'
  # config.salesforce.secret = 'acb123'
  # config.salesforce.callback_url = "https://127.0.0.1:9292/oauth/callback?provider=salesforce"
  # config.salesforce.scope = "full"
  # config.salesforce.user_info_mapping = {:email => "email"}

  # --- user config ---
  config.user_config do |user|
    # -- core --
    # specify username attributes, for example: [:username, :email].
    # Default: `[:email]`
    #
    # user.username_attribute_names =


    # change *virtual* password attribute, the one which is used until an encrypted one is generated.
    # Default: `:password`
    #
    # user.password_attribute_name =


    # downcase the username before trying to authenticate, default is false
    # Default: `false`
    #
    # user.downcase_username_before_authenticating =


    # change default email attribute.
    # Default: `:email`
    #
    # user.email_attribute_name =


    # change default crypted_password attribute.
    # Default: `:crypted_password`
    #
    # user.crypted_password_attribute_name =


    # what pattern to use to join the password with the salt
    # Default: `""`
    #
    # user.salt_join_token =


    # change default salt attribute.
    # Default: `:salt`
    #
    # user.salt_attribute_name =


    # how many times to apply encryption to the password.
    # Default: `nil`
    #
    # user.stretches =


    # encryption key used to encrypt reversible encryptions such as AES256.
    # WARNING: If used for users' passwords, changing this key will leave passwords undecryptable!
    # Default: `nil`
    #
    # user.encryption_key =


    # use an external encryption class.
    # Default: `nil`
    #
    # user.custom_encryption_provider =


    # encryption algorithm name. See 'encryption_algorithm=' for available options.
    # Default: `:bcrypt`
    #
    # user.encryption_algorithm =


    # make this configuration inheritable for subclasses. Useful for ActiveRecord's STI.
    # Default: `false`
    #
    # user.subclasses_inherit_config =


    # -- remember_me --
    # How long in seconds the session length will be
    # Default: `604800`
    #
    # user.remember_me_for =


    # -- user_activation --
    # the attribute name to hold activation state (active/pending).
    # Default: `:activation_state`
    #
    # user.activation_state_attribute_name =


    # the attribute name to hold activation code (sent by email).
    # Default: `:activation_token`
    #
    # user.activation_token_attribute_name =


    # the attribute name to hold activation code expiration date.
    # Default: `:activation_token_expires_at`
    #
    # user.activation_token_expires_at_attribute_name =


    # how many seconds before the activation code expires. nil for never expires.
    # Default: `nil`
    #
    # user.activation_token_expiration_period =


    # your mailer class. Required.
    # Default: `nil`
    #
    user.user_activation_mailer = UserMailer


    # when true sorcery will not automatically
    # email activation details and allow you to
    # manually handle how and when email is sent.
    # Default: `false`
    #
    # user.activation_mailer_disabled =


    # activation needed email method on your mailer class.
    # Default: `:activation_needed_email`
    #
    # user.activation_needed_email_method_name =


    # activation success email method on your mailer class.
    # Default: `:activation_success_email`
    #
    # user.activation_success_email_method_name =


    # do you want to prevent or allow users that did not activate by email to login?
    # Default: `true`
    #
    # user.prevent_non_active_users_to_login =


    # -- reset_password --
    # reset password code attribute name.
    # Default: `:reset_password_token`
    #
    # user.reset_password_token_attribute_name =


    # expires at attribute name.
    # Default: `:reset_password_token_expires_at`
    #
    # user.reset_password_token_expires_at_attribute_name =


    # when was email sent, used for hammering protection.
    # Default: `:reset_password_email_sent_at`
    #
    # user.reset_password_email_sent_at_attribute_name =


    # mailer class. Needed.
    # Default: `nil`
    #
    user.reset_password_mailer = UserMailer


    # reset password email method on your mailer class.
    # Default: `:reset_password_email`
    #
    # user.reset_password_email_method_name =


    # when true sorcery will not automatically
    # email password reset details and allow you to
    # manually handle how and when email is sent
    # Default: `false`
    #
    # user.reset_password_mailer_disabled =


    # how many seconds before the reset request expires. nil for never expires.
    # Default: `nil`
    #
    # user.reset_password_expiration_period =


    # hammering protection, how long in seconds to wait before allowing another email to be sent.
    # Default: `5 * 60`
    #
    # user.reset_password_time_between_emails =


    # -- brute_force_protection --
    # Failed logins attribute name.
    # Default: `:failed_logins_count`
    #
    # user.failed_logins_count_attribute_name =


    # This field indicates whether user is banned and when it will be active again.
    # Default: `:lock_expires_at`
    #
    # user.lock_expires_at_attribute_name =


    # How many failed logins allowed.
    # Default: `50`
    #
    # user.consecutive_login_retries_amount_limit =


    # How long the user should be banned. in seconds. 0 for permanent.
    # Default: `60 * 60`
    #
    # user.login_lock_time_period =

    # Unlock token attribute name
    # Default: `:unlock_token`
    #
    # user.unlock_token_attribute_name =

    # Unlock token mailer method
    # Default: `:send_unlock_token_email`
    #
    # user.unlock_token_email_method_name =

    # when true sorcery will not automatically
    # send email with unlock token
    # Default: `false`
    #
    # user.unlock_token_mailer_disabled = true

    # Unlock token mailer class
    # Default: `nil`
    #
    # user.unlock_token_mailer = UserMailer

    # -- activity logging --
    # Last login attribute name.
    # Default: `:last_login_at`
    #
    # user.last_login_at_attribute_name =


    # Last logout attribute name.
    # Default: `:last_logout_at`
    #
    # user.last_logout_at_attribute_name =


    # Last activity attribute name.
    # Default: `:last_activity_at`
    #
    # user.last_activity_at_attribute_name =


    # How long since last activity is the user defined logged out?
    # Default: `10 * 60`
    #
    # user.activity_timeout =


    # -- external --
    # Class which holds the various external provider data for this user.
    # Default: `nil`
    #
    user.authentications_class = AuthProvider


    # User's identifier in authentications class.
    # Default: `:user_id`
    #
    user.authentications_user_id_attribute_name = :user_auth_id


    # Provider's identifier in authentications class.
    # Default: `:provider`
    #
    # user.provider_attribute_name =


    # User's external unique identifier in authentications class.
    # Default: `:uid`
    #
    # user.provider_uid_attribute_name =
  end

  # This line must come after the 'user config' block.
  # Define which model authenticates with sorcery.
  config.user_class = "UserAuth"
end

Hi, @daichi0410. Would you mind including the full stack trace and sanitizing any private information? At first glance, I see nothing wrong with your configuration file, so I suspect the issue is somewhere else.

Also, Sorcery doesn't define or call encode anywhere, as far as I can tell. Is it possible your code is expecting a value of encode to be included on the resulting user hash?

@joshbuker

Sorry could you let me know the full stack trace and sanitizing any private information meanings? What kind of informations should I share ??

Also, Sorcery doesn't define or call encode anywhere, as far as I can tell. Is it possible your code is expecting a value of encode to be included on the resulting user hash?

Please check below error flows. and let me share controller files below.

class OauthsController < ApplicationController
  
  def oauth
    logout
    if params[:registration_status].present?
      cookies[:registration_status] = params[:registration_status]
    end
    if params[:redirect_url]
      cookies[:redirect_url] = params[:redirect_url]
    end
    login_at(auth_params[:provider])
  end

  def callback
    provider = auth_params[:provider] → the value of provider will be `facebook`
    @user_auth = login_from(provider) → errors happens
~
  end

Herewith the error flows image.

スクリーンショット 2022-09-20 15 47 41

Is it should be errors of Oatuh2 ?

@daichi0410 It looks like you're hitting this block of code:

case response.status
when 301, 302, 303, 307
  opts[:redirect_count] ||= 0
  opts[:redirect_count] += 1
  return response if opts[:redirect_count] > options[:max_redirects]

  if response.status == 303
    verb = :get
    opts.delete(:body)
  end
  request(verb, response.headers['location'], opts)
when 200..299, 300..399
  # on non-redirecting 3xx statuses, just return the response
  response
when 400..599
  error = Error.new(response)
  raise(error) if opts.fetch(:raise_errors, options[:raise_errors])

  response.error = error
  response
else
  error = Error.new(response) # <- This is the line you're hitting
  raise(error, "Unhandled status code value of #{response.status}")
end

Facebook is returning an HTTP Code that the OAuth2 library doesn't recognize. Then OAuth2 breaks when trying to raise an error.

I'm honestly not sure what on earth is going on there, and as far as I can tell this is probably a problem with OAuth2 and not Sorcery.

I would maybe ask the OAuth2 folks here: https://gitlab.com/oauth-xx/oauth2

I would also recommend trying to recreate this issue with a new Rails app, using as little code as possible to aid in debugging.

@joshbuker

I see..
OK, I'll try to folk from them , and create new small Apps.

Thanks☺️

Reposting my response to the Gitlab issue on the oauth2 tracker here.

You are using oauth2 version 1.4.8, and there have been a few bug fixes. There was a breaking change that was accidentally introduced, and then corrected. Please update to the latest 1.4.x series (currently 1.4.11) with:

bundle update oauth2

Let me know if that fixes the issue for you.
In general you should always try the latest patch of a tool to see if that fixes your issue.

konyu commented

@daichi0410
Of course, you have to use the latest gems for the problem.
Before that, Could you check the Facebook API version?

Your part of the codes showed

config.facebook.api_version = "v2.8"

v2.8 looks outdated version.

ref: #322 (comment)

Could you please read the following link and "APIのバージョン" section? It would help if you were Japanese.

https://qiita.com/aiandrox/items/ca798da0bca617074795#4-api%E3%81%AE%E3%83%90%E3%83%BC%E3%82%B8%E3%83%A7%E3%83%B3

@pboling
@konyu

Thank you for your kind advices.
I just updated oauth2 from 1.4.8 to 1.4.11, then my FB login and registration worked!!!

I can't describe how my feelings...
I deeply appreciate for your helps🙇

@daichi0410 I am so happy to hear it worked!! 💯

@pboling

Thank you hundred times😭
Then I closed this issue with many thanks !!!