Asp.Net MVC 5 Owin Twitter Auth throwing 401 Exception - twitter

I have set up OAuth authentication using the Owin middleware based off the default project that gets created when starting a new Web project using "Individual accounts" authentication.
I've tweaked it a bit, but Facebook and Google are working great, however, when I click on the "twitter" button to issue the challenge, it's throwing a 500 http exception with the error message:
Response status code does not indicate success: 401 (Unauthorized).
This only comes up with Twitter. Here is my auth config:
// Just a configuration section that reads from the web.config
var configuration = new OwinCookieConfigurationSection("owinCookieConfiguration");
app.UseCookieAuthentication(GetCookieAuthenticationOptions(configuration));
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwitterAuthentication(
consumerKey: "XXX",
consumerSecret: "XXX"
);
app.UseFacebookAuthentication(
appId: "XXX",
appSecret: "XXX"
);
app.UseGoogleAuthentication();
It's definitely a 500 error, not a 401 error as it indicates and I have confirmed it never makes it passed the original post challenge to Twitter. The stack trace appears to show Twitter is not returning a success code from the ObtainRequestToken call:
Any ideas?

You need to go into the Twitter Dev App and add a website address. I know it seem silly but this will solve your problem.
https://apps.twitter.com/
Go to the Settings Tab
Set a CallBack URL to any website. Even if it is not real.
This should solve you problem.

I solved my problem the way Patrick described 1 year ago. Today I ran into the same issue again but this time I found the issue was caused because of the date/time setting in my computer.
Since the date/time in this computer is usually out-of-sync I had to go to "Change Date and Time settings" -> "Internet Time" tab and enable internet sync.

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.

Instagram oauth api gives { "code": 400, "error_type": "OAuthException", "error_message": "No matching code found." }

I am working on an application that integrates with Instagram API to access the user information. I successfully fetch the Access Token using the authorize url but unable to fetch the userId using access_token url:
i am tried both the endpoints:
https://api.instagram.com/oauth/access_token?client_id=48275564e2c445f6b8e1356djfha3e0c&client_secret=ab2062da9f314e3489dke7ae9cbe6e5d&redirect_uri=http://localhost&grant_type=authorization_code
https://api.instagram.com/oauth/access_token
with the post body as:
client_id=48275564e2c445f6b8e1356djfha3e0c&client_secret=ab2062da9f314e3489dke7ae9cbe6e5d&redirect_uri=http://localhost&grant_type=authorization_code&code=1351860224.4827556.5dc92c4d15ea4a4ea1b0d33eaf0eef19
(The data in the request is modified), But i am getting the follwing
{
"code": 400,
"error_type": "OAuthException",
"error_message": "No matching code found."
}
I have seen tons of queries and questions but could not find any solution to the problem.
The couple of questions i have is:
1) is the field code in the URL is same as access_token, if not how could i get the code field's value.
2) is there any other mechanism(API) to fetch the user details given the username is not known.
Please help me as i am completely stuck and running out my deadlines.
For me unchecking Disable implicit OAuth in instagram developer -> manage clients fixed the issue
I found that using either form-data or application/x-www-form-urlencoded works fine. The most important is the code you get from redirect uri is only used by one request. It means you could request the access token once for the code. If the you request more than one time with same code, you'll get the error like this:
{
code: 400,
error_type: "OAuthException",
error_message: "Matching code was not found or was already used."
}
Wish you all the best ;)
Try to urlEncode the redirect_uri param to
http%3A%2F%2Flocalhost
And your code param contains the "." character which might be a error.
code=1351860224.4827556.5dc92c4d15ea4a4ea1b0d33eaf0eef19
might caused the problem
"error_message": "No matching code found."
"5dc92c4d15ea4a4ea1b0d33eaf0eef19" seems to be the correct code
I got same error. It seems that instagram's spam system disable user's access to any non-official application. Just change user's password. In my case it was help.
Also try create another application.
UPD
From my answer to another question
It looks like users get more than one code, and you see first code, but need second. Try relogin users, if you gets error. User will not see instagram page with confirm button, just redirections.
Possible algorithm of error:
1. User click auth link.
2. Get first code.
3. User click auth link (twice, redirection problem, public auth system, etc.)
4. Get another code (even on the same client_id, redirect_uri).
5. You get first code.
6. But first code already doesn't exists.
The problem is here that need redirect url set as http://localhost/signin-instagram
signin-instagram part is very important
So go to Instagram.com/developer ->Manage Client-> Security -> Valid redirect URIs set with that end http:/../signin-instagram
Off late instagram python snippet fails due to missing content-type HTTP header
response, content = http_object.request(url, method="POST", body=data,headers = {"Content-type": "application/x-www-form-urlencoded"})
adding application/x-www-form-urlencoded worked for me
I will mention what worked for me.
Step 1. Generate a new client secret from you panel.
Step 2. Follow the step 1 mentioned here to obtain the code again.
Step 3. Send the request again with the changed parameters.
Make sure you are logged in the browser when you send the request. You will get the required response.
Go into Facebook for Developers > Your app. Click on "Roles" and add an Instagram test-account under "Instagram Testers".
Log into instagram.com and go to: Settings > Security > Apps and Websites, where you will accept the test invitation.
Prepare your URL link, which you will paste into the web browser. Make sure to use a valid redirect URI from "Valid OAuth Redirect URIs" from the Instagram Basic Display settings.
If you did everything right, the Instagram tester account for the app, will have the option to gain access to user_profile,user_media. Continue the process to get the code which you can exchange for a short-lived access token.

HybridAuth Twitter Failure 401

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.

Facebook login on iPhone thowing errors

I have seen several past questions in SO, but none of them see to answer the question.
I am trying to have my iphone webapp use the Facebook login, but it fails everytime with a 191 error:
An error occurred with My Dev app. Please try again later.
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.
My FB logging link looks like such:
http://m.facebook.com/dialog/oauth/?scope=email,user_birthday&client_id=1754645158****&redirect_uri=http://dev.someDomain.com&display=touch
Post trying to following the link the return uri is stripped from the url:
http://m.facebook.com/dialog/oauth/?scope=email,user_birthday&client_id=1754645158*****&redirect_uri=&display=touch
Per the fb dev site when specifying the domain:
If set, Facebook will enable authentication on all subdomains (e.g., "example.com" will enable *.example.com)
when I change it to my main domain, it redirects correctly.
What gives?
So I think I figured it out, adding www:
redirect_uri=http://www.dev.some
instead of:
redirect_uri=http://dev.some
Seems to fix this, now to finish the rest of the login...

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