youtube oauth works from localhost, but not from production - oauth

The website I'm making makes it possible to connect your account with your youtube account. From localhost, this works perfectly, but from the site, which is step1tuts.appspot.com, it doesn't work. When I redirect the user to the authentication page from my website, I get the following message:
The page you have requested cannot be displayed. Another site was
requesting access to your Google Account, but sent a malformed
request. Please contact the site that you were trying to use when you
received this message to inform them of the error.
The code that handles this authentication looks like this:
client = youtube.get_client()
client.developer_key = 'AI39si759T7YcZ4E3XvICpZr3cGwQ0Ev4AjwyJrVSS6AW6NUc7_t10DX1JsngWzU4YoGjpsjAUTejav0hgXp9vDuM7a83tDXzQ'
client.client_id = 'step1tuts.com'
domain = 'http://' + os.environ['HTTP_HOST']+"/user/youtube_token"
scope = 'http://gdata.youtube.com'
url = client.GenerateAuthSubURL(domain,scope,secure=False,session=True)
self.redirect(str(url))
return
The url I'm redirecting to, ending in /auth_token then processes the token it gets back from youtube, but the error happens here.
Just for clarity, the youtube.get_client method is one that I developed to reuse the process of making the client appengine ready: the code for that is:
def get_client():
client = gdata.youtube.service.YouTubeService()
run_on_appengine(client)
client.developer_key = 'AI39si759T7YcZ4E3XvICpZr3cGwQ0Ev4AjwyJrVSS6AW6NUc7_t10DX1JsngWzU4YoGjpsjAUTejav0hgXp9vDuM7a83tDXzQ'
client.client_id = 'step1tuts.com'
user = users.get_current_user()
if(user and user.yt_token):
client.SetAuthSubToken(user.yt_token)
return client
While pasting in this code, I noticed that I'm duplicating the part where I give my developer key. I don't think that that's the problem, but I'll remove that from the authentication part of my code, and see what happens.
The problem must be tracable by watching the url that the user is redirected to, so just for some extra info, the url that I'm redirected to when I'm using the app on my local machine using the SDK, with which it works:
http://www.youtube.com/auth_sub_request?scope=http%3A%2F%2Fgdata.youtube.com&session=1&next=http%3A%2F%2Flocalhost%3A8081%2Fuser%2Fyoutube_token%3Fauth_sub_scopes%3Dhttp%253A%252F%252Fgdata.youtube.com&secure=0&hd=default
And the url that I'm redirected to when I use the same code on production:
http://www.youtube.com/auth_sub_request?scope=http%3A%2F%2Fgdata.youtube.com&session=1&next=http%3A%2F%2Fstep1tuts.appspot.com%2Fuser%2Fyoutube_token%3Fauth_sub_scopes%3Dhttp%253A%252F%252Fgdata.youtube.com&secure=0&hd=default

Interesting. All other urls work except this one. Probably a bug on youtube side? I just added a '.' at the end of your domain and the request seems to go through. Maybe you can try that?
http://www.youtube.com/auth_sub_request?scope=http%3A%2F%2Fgdata.youtube.com&session=1&next=http%3A%2F%2Fstep1tuts.appspot.com.%2Fuser%2Fyoutube_token%3Fauth_sub_scopes%3Dhttp%253A%252F%252Fgdata.youtube.com&secure=0&hd=default

Related

Problem authenticating with SharePoint Online when using GetWebLoginClientContext

We've got an ASP.NET MVC web application running on Azure on which we want to expose search results from a SharePoint Online tenant. Users in the web app are authenticated on Azure AD, and we want to have them search as themselves (preserving their identity and not use a system account) so that they only see items in the search results that are relevant to them. I thought this would be quite a common requirement.
Using the SharePointPnPCoreOnline CSOM extentions, we were able to retrieve search results with:
var authManager = new OfficeDevPnP.Core.AuthenticationManager();
ClientContext clientContext = authManager.GetWebLoginClientContext("https://xxxxxx.sharepoint.com");
KeywordQuery keywordQuery = new KeywordQuery(clientContext);
keywordQuery.QueryText = "queryText";
SearchExecutor searchExecutor = new SearchExecutor(clientContext);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
clientContext.ExecuteQuery();
(The GetWebLoginClientContext method pops a new window which asks for user credentials if they are not already authenticated. Ideally we would like to have it done silently, but this was the only method wa managed to get working.)
During dev everything was working OK - we were getting the expected search results. However, once we published the web app to Azure we got the following error when trying to search:
502 - Web server received an invalid response while acting as a gateway or proxy server.
There is a problem with the page you are looking for, and it cannot be displayed. When the Web server (while acting as a gateway or proxy) contacted the upstream content server, it received an invalid response from the content server.
One of the suggestions we found for solving http 502 errors was to clear the browser cache, but after we done so it no longer worked on the dev machine either. Instead of displaying a popup requesting user credentials, the popup now just displays the SharePoint Online tenant home page without any login prompt.
Does anyone have an explanation for this?
Or if not, a better way to have users search SharePoint Online without the popup displayed by the GetWebLoginClientContext method?
Solved this in the end not with the GetWebLoginClientContext method (which pops a window for the user to enter credentials) but with the GetAzureADWebApplicationAuthenticatedContext method which authenticates silently using an oauth access token. The problem was obtaining the right token to pass to the method, which we succeeded in doing by using MicrosoftGraphHelper.GetAccessTokenForCurrentUser(url) found here

Call to Micosoft OAuth2 not working as expected

I have an internal corporate web app that needs to access corporate SharePoint Online. I want to call OAuth2 to take the user through the authentication process so the web app can retrieve an access_token and then call the Microsoft Graph API. I am using Django/Python.
I have registered the app in the corporate Azure Portal, but when I call the /authorize endpoint the user sees what appears to be the wrong login page. I expect the user to see a page that shows the app's name and permissions, but all the user sees is a basic sign-on page. Moreover, when the user enters his corporate email address he sees an error that says “There was an issue looking up your account”. The user has been added to the register app's "Users and Groups".
As far as I can tell, everything is configured correctly.
I have Googled this like mad, but not found any help.
Any suggestions would be greatly appreciated.
Thanks.
****************** Problem solved! **************************
As it turns out, I was under the mistaken assumption that the call to the Microsoft /oauth2/v2.0/authorize endpoint should be made in the Django View code on the server (and the response of the call returned to the browser). However, an example on the Internet showed me that the call should actually be made in the browser.
In the example, the URL is constructed on the server and send to to the browser as an Anchor tag like so:
loginUrl = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize"
loginUrl += "?client_id={client id}"
loginUrl += "&response_type=code"
loginUrl += "&redirect_uri=" + request.build_absolute_uri(reverse('auth'))
loginUrl += "&response_mode=query"
loginUrl += "&scope={scope names}"
loginUrl += "&state={state}"
return HttpResponse('Click here to log in to Microsoft Online.')
This works when I am running in my dev environment (http://127.0.0.1:8000) and from an AWS Linux server.
I hope this helps someone in the future.

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

Problems with redirection while implementing oAuth2 for blackberry using webworks

I am trying to implement a SoundCloud app for blackberry phones using webworks frame work.
I am using OAuth2 scheme for authorization. So far I am able to display the SoundCloud log-in page from where the user can allow the app. But the problem occurs during the redirect which is essentially done by SoundCloud. The redirect page which is being pointed to by the call back URI is residing in my device, but after the user approves the app I get a page saying "something went wrong". However when I try to bounce the redirect from a third server, it just works fine. In this case I specify the callback URL pointing to a page on a website which only forwards the request to the page which is residing on my device. But the problem is that I do not want to use this "bounce server"
Could you please look into the code and advise if I am doing something wrong.
/**
* Authenticates the app against soundcloud
* This javascript method is called in the index.htm of my application.
*/
authenticate : function(){
var url = "https://soundcloud.com/connect?" + "scope=nonexpiring&client_id=MY_CLIENT_ID&" +
"response_type=code&redirect_uri=local:///testpage.htm";
window.location = url;
;
/************************************/
testpage.htm only displays "hello sound cloud".
Any help in this regard shall be highly appreciated.
The value for the redirect_uri parameter must match the value of the "Redirect URI" on the app edit page.
Example: https://img.skitch.com/20120411-q6yqada29tcadnep15jc6q75a1.jpg
IHTH
Hannes
The problem is the triple slash part in your redirect_uri. Although, it is a valid URI according to the RFC 3986, the Ruby URI library behaves a bit strange when parsing such values. We're working on a fix.
In the meantime, could you try to use local:/testpage.htm?

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