我正在尝试配置一个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
型
1条答案
按热度按时间pw136qt21#
使用ngrok修复您的问题,您可以查看here