HybridAuth Twitter Failure 401 - twitter

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

So HERE's what happened and what you should know:
Twitter keeps track of the current time
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.

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.

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.

Related

Auth0 checkSession call to renew return an HTML error page

I have a Single Page App using Auth0 Implicit Flow with Silent Authentication. I got the authentication part working just fine, but when I try to implement checkSession method to renew the session in the background (as per https://auth0.com/docs/libraries/auth0js/v9#using-checksession-to-acquire-new-tokens), the AJAX call to the auth0.com domain returns a 400 HTML error instead of a JSON one.
webAuth.checkSession({}, function (err, authResult) {
...
});
The error is Oops!, something went wrong, which I can see in my browser devtools Network Response tab.
There could be a misconfiguration in the system or a service outage. We track these errors automatically, but if the problem persists feel free to contact us.
Please try again.
I am not sure why there would be an HTML response, and not sure what I might be doing wrong. I have added my page's domain to the "Allowed Web Origins" list on the Auth0 application settings.
What I was missing was providing the redirectUri parameter to the checkSession call.
I also found out that I could find logs to these errors by going to the "Logs" menu on the Auth0 dashboard.

Account linking with actions on google

I am facing an issue regarding account linking in Actions on Google:
I am able to authenticate the user and access his email address and username however after this how can I redirect the user back to the google assistant and close the browser where he was authenticated?
Any help will be appreciated!
Update: Hey Prisoner thanks a lot for that.
I did what you said and yeah now it does redirect to google.com but without result_code=SUCCESS when I test it in the simulator.
The link is:
https://www.google.co.in/?gws_rd=cr&dcr=0&ei=z77fWbjQGIXxvATs_oqwBA
Now if I type talk to... again it shows me the message you need to link your account!
In the device the browser automatically closes and it shows SIGNING_IN however when I type an intent it is not recognized.
It would be great if you could point me in the right direction! (I am not sure but I might be at the token exchange stage that you mentioned, but I don't have a clue how to proceed!)
Update 2: As requested the entire flow that I am following:
This is the URL that I receive from debugInfo:
https://assistant.google.com/services/auth/handoffs/auth/start?account_name=cha***#gmail.com&provider=***_dev&scopes=email&return_url=https://www.google.com/
When I paste this in the browser the request that I receive at the authorization endpoint is:
ImmutableMultiDict([
('response_type', 'code'),
('client_id', ****.apps.googleusercontent.com'),
('redirect_uri', 'https://oauth-redirect.googleusercontent.com/r/****'),
('scope', 'email'),
('state', ' CtcCQUxWM2ROU3hNMjl4LUItVXhQSGd4THRMLU4yNExnb3lYbGRKQnQwa3NwTVFva19NUWpYNE5jNGJURzIyZFN3RDBXd2d4enFGVWJGb0Q0ZW1vaS1OaFdkaHdhb05HZ2xlWTR6SllKVlRWYktwd09faklyUTVheFhQbGw2dmVKYzVFTk05N3B1QkxaZG41RVdHN0wyTktvRFdCYzFPVFBzM1dQUlFtN2RmM1VtRU4****(state)')
])
The response (redirect_url) that I send back:
https://accounts.google.com/o/oauth2/v2/auth?scope=email&response_type=code&redirect_uri=https%3A%2F%2F******.herokuapp.com%2Fcallback%2Fgoogle&client_id=****.apps.googleusercontent.com
When it reaches my endpoint again the request arguments are:
ImmutableMultiDict([
('code', '4/***********')
])
Now I am able to access the email address and other details
The url that I redirect to from here:
https://oauth-redirect.googleusercontent.com/r/****?code=abcdefgh&state=CtcCQUxWM2ROU3hNMjl4LUItVXhQSGd4THRMLU4yNExnb3lYbGRKQnQwa3NwTVFva19NUWpYNE5jNGJURzIyZFN3RDBXd2d4enFGVWJGb0Q0ZW1vaS1OaFdkaHdhb05HZ2xlWTR6SllKVlRWYktwd09faklyUTVheFhQbGw2dmVKYzVFTk05N3B1QkxaZG41RVdHN0wyTktvRFdCYzFPVFBzM1dQUlFtN2RmM1VtRU4****(state)
This redirects me to :
https://www.google.co.in/?gws_rd=cr&dcr=0&ei=5c_fWdfKNYndvASO7o6ACA
Edit 3: I checked the network logs:
result_code=FAILURE&result_message=Account+linking+failed
I also added /token/google as the token URL in AoG. It is detected in heroku however I never receive this request in my code.
Note: I am using python flask and hosting my app on heroku
Once you have authenticated the user, you'll need to return a temporary auth code back to Google. Later, Google will exchange this auth code for an access token and a refresh token, but you're not there yet. The important part is that this code needs to be unique and that, later, you'll be able to recognize what user it is for. The code should be valid for a limited time - 10 minutes is a generally accepted time frame.
In the request Google sent to you as part of the login, they've provided a redirect_uri and a state as parameters. You'll need to use these in your reply. (state can be anything - you shouldn't care what it is, you're just going to send it back with your redirect. Its purpose is to improve security by preventing replay attacks.)
Verify that the redirect_uri has the form
https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
Where YOUR_PROJECT_ID is... you guessed it, the ID of your project. You can find this in the cloud console.
You'll then redirect the user to this URL with a few additional parameters:
https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID?code=AUTHORIZATION_CODE&state=STATE_STRING
Where YOUR_PROJECT_ID is as noted above, AUTHORIZATION_CODE is the code you've generated, and STATE_STRING is the value of the state parameter that you were sent in the request.
For details, you can see https://developers.google.com/actions/identity/oauth2-code-flow#handle_user_sign-in

Check if user still has the app connected to their SoundCloud account?

When a user connects to my SoundCloud web app and then disconnects it through their SoundCloud settings, my app stops working and returns a 401 error:
Error Code 500
The requested URL responded with HTTP code 401.
I'm using the SoundCloud PHP library.
Currently on connecting I save the user's Soundcloud User ID to a session and database, and I save the oauth token and secret to a database.
What happens is when the user hits Connect on my website after disconnecting the app from their SoundCloud settings is the following:
Code checks the user's SoundCloud ID and tries to authenticate using the OAuth credentials saved to the database.
Since the user disconnected from the app, the OAuth credentials no longer work and returns an access denied error.
I'm looking for a way to detect this error and remove the database entry containing the no longer working OAuth token in order to allow the user to properly reconnect.
I tried with the following code:
$result = User::model()->findByAttributes(array("oauth_uid"=>$_SESSION['scid']));
//If result is empty create login URL
if(empty($result)){
$sc_auth = false;
$scloginurl = $client->getAuthorizeUrl(array("scope"=>"non-expiring"));
//Else if result is found, try setting the access token, if access token returns errors get login URL
}else{
try{
$client->setAccessToken($result['oauth_token']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e){
$scloginurl = $client->getAuthorizeUrl(array("scope"=>"non-expiring"));
$sc_auth = false;
$error = 1;
}
As you can see above, I tried using 'try() catch()' to see if there's any errors from setting the access token, however the website seems to return the same error and not execute any of the code in catch().
Solved it by going into the SoundCloud.php file from SoundCloud's PHP Library and replacing the code of
throw new Services_Soundcloud_Invalid_Http_Response_Code_Exception( .... );
with my code to remove the database entry and reload the window!
A little wonky since it will remove the entry regardless of exception, but it works!

LinkedIn Oauth error: 'The partner did did not properly implement the authentication protocol' on browser back after signin

We integrated a Rails app with linkedin authentication, using devise and the linkedin gem.
It works fine and able to register/sign in with linkedin, however an odd thing happens when you press 'back' on the browser after signing in/up:
It goes back to linkedin with the same request URL and the error shown is:
The partner did did not properly implement the authentication protocol. in RED
This looks quite bad and we'd like to have a better way of handling this, but no idea where to start; any idea what could trigger this and is there any way we can prevent it?
You will need to build your service for every new request.You might have same access code for diff-2 request.
Try to generate it for every http auth request.
service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(API_KEY)
.apiSecret(API_SECRET).debug()
.build();

Keep getting OAuth::Unauthorized error when using oauth and twitter ruby gems

I am using the ruby twitter gem and oauth to gain access to users twitter accounts. In my code, I have:
unless #user.twitter_authd?
oauth = Twitter::OAuth.new('token', 'secret')
session[:twitter_request_token] = oauth.request_token.token
session[:twitter_request_secret] = oauth.request_token.secret
#twitter_auth_url = oauth.request_token.authorize_url
end
where token and secret have my actual token and secret inserted. When I click on the link to the #twitter_auth_url, I am taken to twitter and asked to grant access. I click allow and then twitter redirects me to my callback URL http://www.mydomain.com/twitter_callback/?oauth_token=fmy2aMvnjVgaFrz37bJ4JuB8r5xN79gsgDQRG4BNY which then hits this code:
oauth = Twitter::OAuth.new('token', 'secret')
logger.info("session[:twitter_request_token] = #{session[:twitter_request_token]}")
logger.info("session[:twitter_request_secret] = #{session[:twitter_request_secret]}")
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
session[:twitter_request_token] = nil
session[:twitter_request_secret] = nil
#user.update_attributes({
:twitter_token => oauth.access_token.token,
:twitter_secret => oauth.access_token.secret,
})
redirect_to root_path
The twitter request token and secret are being set just fine. However I end up with an authorization error:
OAuth::Unauthorized in MainController#twitter_callback
401 Unauthorized
RAILS_ROOT: /Users/TAmoyal/Desktop/RoR_Projects/mls
Application Trace | Framework Trace | Full Trace
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/consumer.rb:167:in `token_request'
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/tokens/request_token.rb:14:in `get_access_token'
/Library/Ruby/Gems/1.8/gems/erwaller-twitter-0.6.13.1/lib/twitter/oauth.rb:29:in `authorize_from_request'
/Users/TAmoyal/Desktop/RoR_Projects/mls/app/controllers/main_controller.rb:70:in `twitter_callback'
The code is failing at this line:
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
when it tries to get an access token. You can see the source code of authorize_from_request here. I am not sure why this is happening. Anyone have ideas?
A bit late to the party but just ran into the same issue myself. I tracked the issue down to the setup of my OAuth app in Twitter. I had initially not specified a callback URL as I was unsure of it.
Once I had setup my rails app I went back to find Twitter had assumed I was a desktop application as I hadn't specified a callback URL. Once I changed this to website and entered a callback URL I stopped getting 400s.
If you're getting error 401 - OAuth::Unauthorized, make sure you edit the settings of your Twitter application as follows:
Application Type: Browser
Callback URL: http://127.0.0.1:3000/auth/twitter/callback
this is an issue about time synchronization of your system with twitter server.
Twitter doesn't allow localhost as part of a valid callback URL.
Instead use http://127.0.0.1:3000/auth/twitter/callback
Hope this helps
This was one of the most annoying things to debug that I have come across. I was outputting in a couple places by accident because the URL's are dynamic and they happened to not be defined in my test case (i use this to display chart data and there is not enough right now so the google chart api URL's are blank). This caused my browser to make multiple requests to my localhost when some pages were loaded. Somehow that made the oauth process crap out. Obviously there is no way for people on S.O. to know about my application specific issue so I had to answer my own question.
I had this same problem and none of the suggestions in this thread worked for me.
I found the problem for me was the TIMESTAMP on my request. The mobile device I was running my scripts on had a jacked up clock. When I updated the system time on my device to the correct time (i.e. now), all of my requests came back "200 OK" instead of "401 Unauthorized".
This problem seems to be caused by twitter not being able to handle connection keep-alive correctly. Make sure you set connection=close http header in the request to twitter. Wasted a weekend debugging this.
not enough info for me, but when was twitter gem last updated? twitter changed their oauth 'stuff' in mid may approx. perhaps you have an old one. I'd update your question to show the callback_url, and make sure you have the right token and secret, which it looks like you don't have.
also, did you put the right callback url in your twitter app page? alot of times that screws you up too.
if that fails use mbleighs twitter_auth instead. it worked for me and is pretty slick.

Resources