Google OAuth 2.0 for Titanium is a module for Appcelerator Titanium that i’ve created for use in my mobile apps. It allows to authenticate user with Google OAuth 2.0 and then work with Google Apis.
To understand how it works you must check Google Accounts Authentication and Authorization docs.
Sample usage
Check the demo App to see it in action. It is pretty simple but you will need to get your CLIENT_ID and CLIENT_SECRET from Google Api Console.
//initialize module var GoogleAuth = require('modules/googleAuth'); var googleAuth = new GoogleAuth({ clientId : 'CLIENT_ID', clientSecret : 'CLIENT_SECRET', propertyName : 'googleToken', scope : ['https://www.googleapis.com/auth/tasks', 'https://www.googleapis.com/auth/tasks.readonly'] }); //create some button var sync = Ti.UI.createButton({ title : 'Sync' }); //do some action... sync.addEventListener('click', function() { googleAuth.isAuthorized(function() { Ti.API.info('Access Token: ' + googleAuth.getAccessToken()); //user is authorized so do something... just dont forget to add accessToken to your requests }, function() { //authorize first googleAuth.authorize(); }); });
Demo App
Repository on github.com
All code is open source and dual licensed under GPL and MIT. Feel free to use it.
If you have any question feel free to ask.
Thanks for the wonderful API. I have tried your sample application
I can able to get Access Tocken, but I am getting following error and warning,
Error: “Can’t load tasklists”
[WARN] Unable to securely connect to http://www.googleapis.com with the latest TLS. Trying again with TLS1.0. It is highly suggested that the server be updated to the latest TLS support.
Any Idea?
Hi
1. What is your Titanium SDK version?
2. What is your iOS SDK version?
3. What you get when you try this in your terminal (change access token):
curl https://www.googleapis.com/tasks/v1/users/@me/lists?access_token=ACCESS_TOKEN
I am using Titanium 2.1.0GA and iOS 5.0 sdk.
While trying in Terminal I am getting below response
{
“error”: {
“errors”: [
{
“domain”: “usageLimits”,
“reason”: “accessNotConfigured”,
“message”: “Access Not Configured”
}
],
“code”: 403,
“message”: “Access Not Configured”
}
}
Thanks
You need to enable Task API in your API console.
https://code.google.com/apis/console/ (Services => Task API => ON)
After enabling Task API check again curl in terminal with your new access token.
Thanks Miroslav, It is working fine now.
Thanks for quick response. 🙂
Good job!
Hi!
Thank you for your amazing work!!!
I successfully made it work on iOS emulator, but had a problem on android.
when you setup post request in getToken, the request url should use https, otherwise it will return “method not found” error. I am not sure why this does not happen in iOS…
Thank you again !
Thank you for the info. I’ve raised issue in my repository (http://goo.gl/s7RLF). I will commit new version with bug fix.
Thanks for this API, saved me hours of work to get this done myself! 🙂 Would be nice with some type of wrapper for the Google Apis in a future release. Works perfect out of the box!
Sorry for the late response. Im glad that you are using my library.
Google has about 54 services with api … 🙁 For which service(s) would you like to have wrapper? Maybe i will find some time to create such a wrapper for few services…
Hi my friend! Very good your code.
In IOS is perfect , but in Android we have one problem.
In android is not possible get the token, every time that i do this the answer is null…
Why?? = (
Hi,
can you please specify which versions (titanium, android) are you using?
Thanks
Hi Miroslav Magda , the version of my android is the 2.2
Thanks!
Hi Miroslav Magda , the version of my android is the 2.2
Thanks!
Your code working fine in IOS, But in android it throughs error Method not allow at the time call the getToken function
Am use Android Version :- 2.3.3.
Titanium Version :- 3.0.2.GA
Please help me to solve this problem in Android.
I am integrated your code in Titanium (ios) it is working fine, But facing problem in Titanium(android) .
Every time i am ennter user details for goolge account and redirected to Terms of service page after click on Accept button , googleAuth.isAuthorized() method gives false reponse. Here i am mention my SDK details .
(1) Android version 2.3.6 and above
(2) Titanum SDK 3.1.0.GA
Please give the solution for Android.
Are you using the latest version of library (0.3.2) ?
we are using version = ‘0.3.1’;
Can you pls try it with 0.3.2 (latest) version? You can find latest version on bitbucket (https://bitbucket.org/miroslavmagda/google-auth-for-titanium)
Hi,
I am trying to load it in my alloy project. But it is showing cannot find the file. So can you tell me how to exactly use this file.
Can I just use googleAuth.js in my lib folder and just call it using require? Do I have to use it as a module or just CommonJS will do? Thanx in advance.
Hi,
You can load my library like regular CommonJS module (with require…).
I didn’t use this library with Alloy projects so I cant give you any advice how to integrate it into Alloy project 🙁
Here is a nice guide how to integrate underscore.js / backbone.js to Alloy project (http://docs.appcelerator.com/titanium/3.0/#!/guide/Alloy_Controllers-section-34636384_AlloyControllers-InitializerFile%28alloy.js%29). You can integrate my library exactly like underscore.js.
Hello Miroslav,
i wanted to thank you for the excellent job and ask a question.
Could you please tell me how can i use this to post on Google+?
Thanx in advance
A.
You can use this to authorize requests to Google+ API (https://developers.google.com/+/api/).
Basically working with task API and G+ API is very similar. Example app is working with task API.
What exactly are you struggling with?
I wanted to share just a text on g+. But i cant get it to work.
Can you pls send small snippet of your code so I can look at it and help?
Hello,
Thank you very much for share this project. I have a problem when I try to run the app in Android. Before I run the app, I activate Android in tiapp.xml, and introduce the clientID and clientSecret of Google( I created the project in the Google API like Web Aplication).
The error occurs when I run the app in my device, in the main window it appears only a “Google Tasks” tab that changes the color when I pulse it, but anything else happens.
What can I do?
My Titanium SDK version is 3.1.4. and the Android SDK is 4.1.2 (Google API).
Thank you very much and congratulations for your work.
Hi,
Is there any error message in the console?
Hello,
I managed to fix the error, but now I have other error.
“The redirect URI in the request:
urn:ietf:wg:oauth:2.0:oob did not match a registered URI”
How can I put the correct redirect URI, so that after the login appears the main window of my app?
Thank you very much, and great job.
Hi,
Did you register your app in google API console as “Installed app”?
Hello,
Where is the “Installed app” option in the google API console? It’s “native” option??
I activated “Tasks Api” in API’s, and “web application” in the registered apps. I don’t see the “installed app” option.
Thanks.
Ok, I try with “native” and all is correct.
Do you know how I can view my gmail contacts in my app?I want to choose them and invite then to login.
Thank you very much.
In the new api console its called “native”.
If you want to get your contacts you will need to use g+ API. So the first step will be to set the right scope (scope attribute) and then call the right url (https://developers.google.com/+/api/)
Hi i’m trying to access the user information below is my code where i had changed in authorize function which is in googleauth
function getToken(code, cb) {
Ti.API.info(“inside get token…………………………..”);
Ti.API.info(code + “…………………..” + cb);
cb = (cb) ? cb : function() {
};
var xhr = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info(this.responseText);
var resp = JSON.parse(this.responseText);
// Ti.API.info(resp);
log.info(resp.expires_in);
resp.expires_in = parseFloat(resp.expires_in, 10) * 1000 + (new Date()).getTime();
log.info(resp.expires_in);
Ti.App.Properties.setString(_opt.propertyName + ‘.accessToken’, resp.access_token);
Ti.App.Properties.setString(_opt.propertyName + ‘.refreshToken’, resp.refresh_token);
Ti.App.Properties.setString(_opt.propertyName + ‘.tokenType’, resp.token_type);
Ti.App.Properties.setString(_opt.propertyName + ‘.expiresIn’, resp.expires_in);
_prop.accessToken = resp.access_token;
_prop.refreshToken = resp.refresh_token;
_prop.tokenType = resp.token_type;
_prop.expiresIn = resp.expires_in;
log.debug(_prop);
//alert(‘success’);
win.close();
//callback
cb();
},
// function called when an error occurs, including a timeout
onerror : function(e) {
//log.info(e.error);
//log.info(e.responseText);
//TODO: show some error message
Titanium.UI.createAlertDialog({
title : ‘Error’,
message : _opt.errorText
});
win.close();
},
timeout : 5000 /* in milliseconds */
});
// Prepare the connection.
xhr.open(“GET”, ‘https://www.googleapis.com/oauth2/v2/userinfo’);
xhr.setRequestHeader(‘Content-Type’, ‘application/atom+xml; charset=UTF-8; type=feed’);
var d = {
code : code,
client_id : _opt.clientId,
client_secret : _opt.clientSecret,
redirect_uri : ‘urn:ietf:wg:oauth:2.0:oob’,
grant_type : ‘authorization_code’
};
// Send the request.
xhr.send(d);
}
i had changed the scope and the url am not understanding how to access the user information pls help me
Im not sure what are you trying to do…
If you would like to access user information you dont need to rewrite the library.
Please look at the Google documentation for G+ API: https://developers.google.com/+/api/
There is a example for what you are trying to achieve. You need to authorise with my library (with your credentials) and you will get access token [googleAuth.getAccessToken()]. With that access token you can get data from G+ API:
GET https://www.googleapis.com/plus/v1/people/{userId}?access_token= + googleAuth.getAccessToken()
how to integrate this code in my app.js in my project
please help me….
Did you checked my example app source codes?
https://github.com/ejci/Google-Auth-for-Titanium/blob/master/Example%20App/Resources/app.js
hi, i used your module to get the google calendar data into my titanium app. i got the access token but every time i use it to access the calendar list it gives me “Authorization needed” error. please help.
Thanks in advance
Can you share the code? Is access to calendar data set for the token in Console API?
How can i use ur library for showing the google+ button and login ? I am new to titanium devlopment.I am using it for iPhone dev.
It is possible and it is relatively easy.
Do you have source code that you need help with?
thanks for the response. i have posted the stuff on stackoveflow http://stackoverflow.com/questions/24203698/i-keep-getting-http-403-error-for-google-oauth-2-0-titanium-alloy
Hi please refer toi the question. I have already enabled apis but still it won’t work.
http://stackoverflow.com/questions/24203698/i-keep-getting-http-403-error-for-google-oauth-2-0-titanium-alloy
And i am using 3.2, ios 7.1
USing 3.2.3 GA Titanium and ios 7.1
I get this response when i m trying to retrieve user profile.
{“type”:”load”,”source”:{“cache”:false},”code”:0,”success”:true}
Hi, when I try to call the gDrive api, the return is “error 401” that mean Login Required.
“{
“error”: {
“errors”: [
{“domain”: “global”,
“reason”: “required”,
“message”: “Login Required”,
“locationType”: “header”,
“location”: “Authorization”
}],”code”: 401,
“message”: “Login Required” }}”
I’ve created an “Client ID for installed applications”, then after authorization, in the callback I use:
var _token = googleAuth.getAccessToken();
var webReq = Ti.Network.createHTTPClient({});
webReq.open(“GET”, “https://www.googleapis.com/drive/v2/files?key=” + _token);
webReq.send();
webReq.onload = function(e){
var resp = JSON.parse(this.responseText);
};
webReq.onerror = function(e) {
var resp = JSON.parse(this.responseText);
};
The scopes are https://www.googleapis.com/auth/drive and https://www.googleapis.com/auth/drive.file.
Can anyone help me pls?
Can you please try https://developers.google.com/oauthplayground/ with the credentials you have?
Check please if the console is returning the same you have.
Resolved! 🙂
Can you please share what was the problem (if possible).
Maybe someone will have similar problem in the future…
Hi Matteo ,
Can you please share the solution for this problem ? Because i am trying to integrate gdrive and facing the same issue…!!
Hey Miroslav,
Am I correct to assume that by changing few urls and values (which address Google) to a different server which support OAuth2 it should work? or maybe there is something specific to Google implementation? (doesn’t seems likely….)
Thx!
Yes it should work.
There is nothing “google” specific…
what about this issue
https://github.com/ejci/Google-Auth-for-Titanium/issues/4
Hello Miroslav Magda.
thnx 4 the great work. I am trying to use google + instead of google so would you plz advise me on how to approach?
Open a ticket in github repository with the problem and I will try to help
Hi,
in Google API console, while creating add new client id, what I have to select i.e.
-Web application
-Service account
-Installed application
I selected installed application, in that case do I have to create separate client id for android and iOS to use this library.
Pick “other” and check this https://github.com/ejci/Google-Auth-for-Titanium/issues/4
This works just awsome. Thanks for the great module but is it somehow possible to use the native G+ app for login like Facebook login so users don’t have to enter email and password in browser everytime and it silently login with the credentials stored in G+ app or phone settings account?
How do I register this app to try it out?
When I built this on ios I didn’t have the buttons on the top bar. What would be the reason for this.
Not sure if you are still responding to this but I got it to work on ios. Yet everytime I run it on android it responds with a bad request when I hit sync.
While it was working previously and I’ve used it successfully couple of times, it seems that it no longer works on iOS. When I try to login on iOS, I get a “403 Error: disallowed_useragent”. Apparently Google has stopped allowing the use of webview for OAuth authentication. Does somebody has a solution for it?
Also receiving the “Notice for developers: authorization requestes in embedded browsers will be blocked on April 20, 2017.”
Did you find something?
Hey Carlos, have you found something for this?