Twitter::Error::Unauthorized in PostsController#cr

2019-02-20 17:03发布

问题:

Why does "create" throw me an invalid/expired token error?

The users are able to log in just fine (so they are authenticated properly) but when they try to create a post, I get this error. I'm using Omniauth gem (v1.1.4) for authentication and Twitter gem (v4.6.2) for the posting to Twitter. The Omniauth-twitter gem is v0.0.16 if that matters.

This is the code that is causing me an error

class PostsController < ApplicationController
  def create
    Twitter::Client.new.update(@post.content)
  end
end

This is part of the user model (user.rb)

def twitter
  unless @twitter_user
    provider = self.authentications.find_by_provider('twitter')
    @twitter_user = Twitter::Client.new(:oauth_token => provider.token, :oauth_token_secret => provider.secret) rescue nil
  end
  @twitter_user
end

Here's my omniauth initializer

Rails.application.config.middleware.use OmniAuth::Builder do
  configure do |config|
    config.path_prefix = '/auth'
  end

  provider :twitter, "xxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
end

Twitter.configure do |config|
  config.consumer_key = "xxxxxxxxxxxxxxxxxxxx"
  config.consumer_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  config.oauth_token = :token
  config.oauth_token_secret = :secret
end

my schema:

create_table "authentications", :force => true do |t|
  t.integer  "user_id"
  t.string   "provider"
  t.string   "uid"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
  t.string   "secret"
  t.string   "token"
end

回答1:

You need something like '@twitter_user.update'. For each twitter user you create with 'Twitter::Client.new' you have to provide omniauth's token and secret(like you do it in 'user.rb' model)

class PostsController < ApplicationController
  def create
    # get twitter user. Feel free to change it depending on your app
    @twitter_user = User.twitter
    @twitter_user.update(@post.content)
  end
end


回答2:

I think the current "token" and "secret" in the "authentications" table you are using have been expired.

  • You can simply try deleting all rows in the "authentications" table, then signing in with twitter account again and see whether it is working.
  • Or try setting a breakpoint just after the codes of user getting authenticated with twitter account, then just executing tweet posting lines once you manually set the "token" and "secret" with returned authentication information: ["credentials"]["token"] and ["credential"]["token"]. I think the tweet will be posted.

If it's still not working, you'd better show other related codes like session controller as well. The whole picture of your authentication flow will be more helpful to figure the problem out.