HybridAuth Twitter Failure 401

2019-06-25 12:56发布

问题:

THE PROBLEM I was able to connect to Twitter the the HybridAuth library, and it stopped working. Posting to a Twitter account was also functional.

WHAT I HAVE TRIED Resetting my Twitter app access tokens. Creating an All new Twitter app. Using the HybridAuth debug mode to troubleshoot.

THE ERROR MESSAGE "Authentification failed. The user has canceled the authentication or the provider refused the connection.

Original error message: Authentification failed! Twitter returned an error. 401 Unauthorized."

MY RESEARCH This seems to be attributed to the lack of the key and secret, but I set these in the Twitter config file.

THE CODE

            $hybridauth = new Hybrid_Auth( $config );

            $adapter = $hybridauth->authenticate( "Twitter" );
            $hybridauth_session_data = $hybridauth->getSessionData();
            store_session_data($hybridauth_session_data);

            // get the user profile 
            $user_profile = $adapter->getUserProfile();

The exception is being thrown by the authenticate method. Before it would ask me to allow access via the app and now it throws the error.

If you need more information, please let me know. Rick

回答1:

So HERE's what happened and what you should know:

  1. Twitter keeps track of the current time
  2. If an API request to authenticate comes from a server that claims it is a time that is outside of 15 minutes of Twitter time, it will fail with a 401 error.

HOW I fixed it:

I set my server time to the correct time by using the USNO Master Clock. It happened to be just over 15 minutes offset.



回答2:

This is just another solution which was my case:

Set the "Callback URL" in the Twitter App(If you are testing in local, you can use an example URL).

They didn't specify this as a mandatory field and they allow overriding this URL with the one in the HybridAuth request.



回答3:

in case somebody else cant edit their server time too, there is a workaround for that. The most basic and probably not the cleanest way is just going to Hybrid/thirdparty/OAuth/OAuth.php locating generate_timestamp() function and adding what ever the time discprenecy there is between your server and gtm+0 to the time(). like this:

private static function generate_timestamp() {
return time() + 7200;

}

in my case, my server is gtm-2, so I had to add 2 hours (in seconds) to the time() function in order to make it work.