Google OAuth 2.0 for Titanium

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

Example 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.

63 thoughts on “Google OAuth 2.0 for Titanium

  1. karthi

    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?

    Reply
    1. Miroslav Magda Post author

      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

      Reply
      1. karthi

        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

        Reply
  2. JWK

    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 !

    Reply
  3. Christofer

    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!

    Reply
    1. Miroslav Magda Post author

      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…

      Reply
  4. Mauro Favoretto

    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?? = (

    Reply
  5. Nishanth

    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.

    Reply
  6. Dipesh Jade

    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.

    Reply
  7. Abhinav

    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.

    Reply
    1. Miroslav Magda Post author

      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.

      Reply
  8. Angjelin Serreqi

    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.

    Reply
  9. Daniel Montes

    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.

    Reply
      1. Daniel Montes

        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.

        Reply
        1. Daniel Montes

          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.

          Reply
          1. Daniel Montes

            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.

  10. kusuma

    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

    Reply
    1. Miroslav Magda Post author

      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()

      Reply
  11. viren

    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

    Reply
  12. hemant

    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.

    Reply
  13. hemant

    I get this response when i m trying to retrieve user profile.
    {“type”:”load”,”source”:{“cache”:false},”code”:0,”success”:true}

    Reply
  14. Matteo

    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?

    Reply
        1. nan

          Hi Matteo ,
          Can you please share the solution for this problem ? Because i am trying to integrate gdrive and facing the same issue…!!

          Reply
  15. Nimrod

    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!

    Reply
  16. Abdirahman

    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?

    Reply
  17. Ajeet

    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.

    Reply
  18. Qasim

    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?

    Reply
  19. John

    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.

    Reply
  20. Qasim

    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?

    Reply
    1. Carlos

      Also receiving the “Notice for developers: authorization requestes in embedded browsers will be blocked on April 20, 2017.”
      Did you find something?

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *