Twitter :: Error :: Unauthorized in PostsController # create - Invalid or expired token

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

Users can log in just fine (so they authenticated correctly), but when they try to create a message, I get this error. I use Omniauth gem (v1.1.4) for authentication and twitter jewels (v4.6.2) for posting on Twitter. In this case, the pearl of Omniauth-twitter v0.0.16.

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 is 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 circuit:

 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
source share
2 answers

You need something like "@ twitter_user.update". For each Twitter user that you create using "Twitter :: Client.new", you must specify the omniauth token and secret (for example, you do this in the 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 
0
source

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

  • You can simply try to delete all the lines in the "authentication" table, and then log back in with your twitter account and see if it works.
  • Or try setting a checkpoint immediately after user codes receive authentication using a Twitter account, and then just follow the tweet lines after you manually set the β€œtoken” and β€œsecret” with the authentication information returned: ["credentials" ] ["token"] and ["credentials"] ["token"]. I think a tweet will be posted.

If it still doesn't work, you'd better show other related codes, such as a session controller. The whole picture of your authentication flow will be more useful to understand the problem.

0
source

All Articles