ruby 尝试twitter oauth时获取授权

k97glaaz  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(137)

我正在尝试配置一个Rails 7应用程序,以允许通过twitter ouath登录。点击登录按钮时出现此错误。我尝试使用v1和v2凭据。

错误

COULD NOT AUTHENTICATE YOU FROM TWITTER BECAUSE "401 UNAUTHORIZED".

字符串

Gemfile

# AUTHENTICATION
gem 'activerecord-session_store'
gem 'devise'
gem 'devise-jwt'
gem 'devise_zxcvbn'
gem 'omniauth'
gem 'omniauth-rails_csrf_protection'
gem 'omniauth-twitter'

app/views/devise/sessions/new.html.slim

= link_to 'Sign in with Twitter', user_twitter_omniauth_authorize_path, class: 'btn btn-info default w-100', id: 'twitter-login', method: :post

app/controllers/users/omniauth_callbacks_controller

module Users
  class OmniauthCallbacksController < Devise::OmniauthCallbacksController
    def twitter
      # You need to implement the method below in your model (e.g. app/models/user.rb)
      @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: 'Twitter') if is_navigational_format?
      else
        session['devise.twitter_data'] = request.env['omniauth.auth'].except('extra')
        redirect_to we_vote_root_url
      end
    end

    def failure
      set_flash_message(:alert, :failure, kind: 'Twitter', reason: failure_message) if is_navigational_format?
      redirect_to new_user_session_path
    end
  end
end

config/initializers/devise.rb

config.omniauth :twitter, Rails.application.credentials.dig(:twitter, :api_key), Rails.application.credentials.dig(:twitter, :api_key_secret)

app/models/user.rb

def self.from_omniauth(auth)
    password = Devise.friendly_token[0, 20]
    identity = Identity.find_for_oauth(auth)
    user = identity.user
    user ||= User.find_or_initialize_by(email: auth.info.email)
    user.first_name = auth.info.name.split[0] unless auth.info.name.split.empty?
    user.last_name = auth.info.name.split[1] if auth.info.name.split.length > 1
    user.phone_number ||= auth.info.phone_number
    file = URI.open(auth.info.image)
    user.avatar.attach(io: file, filename: 'avatar.png', content_type: 'image/png')
    user.skip_confirmation!
    if user.encrypted_password.blank?
      user.password = password
      user.password_confirmation = password
    end
    user.save!
    identity.update(user: user) if identity.user.nil?
    user
  end

Twitter门户配置URL

http://localhost:3000/auth/twitter
http://localhost:3000/users/auth/twitter/callback
http://localhost:3000/auth/twitter/callback
http://localhost:3000/users/auth/twitter

相关问题