简体   繁体   中英

Authentication failure! invalid_credentials: OAuth::Unauthorized, 401 Authorization Required

I want to create Twitter login function,but error is occured.

My error is

Authentication failure! invalid_credentials: OAuth::Unauthorized, 401 Authorization Required
Processing by Users::OmniauthCallbacksController#failure as HTML
  Parameters: {"oauth_token"=>"OFSEOwAAAAAA9LdUAAABaAyY_Uc", "oauth_verifier"=>"hogehogehoge"}
Redirected to http://localhost:3000/

initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, 'agfrfgagfkfuauR1U8Busfd4KAiq', 'djkjsgkjgkasjkdfjskajfkjdskfjsk'
end

initializers/divise.rb

 config.omniauth :twitter, ENV['TWITTER_API_KEY'], ENV['TWITTER_API_SECRET'], scope: 'email', oauth_callback: "#{ENV['HOST']}/users/auth/twitter/callback"

routes.rb

 devise_for controllers: { registrations: "registrations", omniauth_callbacks: 'users/omniauth_callbacks' }

controllers/users/ominiauth.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  # callback for twitter
  def twitter
    callback_for(:twitter)
  end

  def callback_for(provider)
    @user = User.from_omniauth(request.env["omniauth.auth"])
    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, kind: "#{provider}".capitalize) if is_navigational_format?
    else
      session["devise.#{provider}_data"] = request.env["omniauth.auth"].except("extra")
      redirect_to new_user_registration_url
    end
  end

  def failure
    redirect_to root_path
  end
end

model/user.rb

devise :omniauthable, omniauth_providers: %i[twitter]
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.email = auth.info.email
      user.password = Devise.friendly_token[0,20]
    end
  end

Please teach me a hint!

Assuming you using gem devise , omniauth-oauth2 & omniauth-twitter ,

Check your API key and API secret provided in your rails app whether it matches from your registered a Twitter app.

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