Google Oauth with WinJs

The WinJS code sample below shows how to implement Google Oauth.

The Oauth mechanism remains almost same for different apis like (Facebook , Twitter etc) only the urls the way of generation of api keys differ.

First of all , you need to generate Api key and secret key from APIs Console. You can visit and as this is a desktop app , let the callback url be http://localhost

Now you have the following parameters with you

var SCOPE = ''; // You can add scopes space separated for the service you want to use
var CLIENTID = 'Your Client ID from Api Console';
var ClIENTSECRET = 'Your Client Secret from API Console here';
var API_KEY = 'API_KEY from Google Apis Console';

Let us write a function for Login in Js now

function Login()
var requesturl = '' +'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type= code';
var requestUri = new Windows.Foundation.Uri(requesturl);
var callbackUri = new Windows.Foundation.Uri("");

callbackUri ).then(callBackOnSuccess, CallBackOnError);

The above code opened up the google login and window would ask for credentials and would prompt user with what all apis your application is going to use(depending on the scopes you mentioned earlier) and would ask user for his consent.

Now this was the call to an async method so we need to have callbacks I.e callBackOnSuccess and CallBackOnError .

Onsuccess , authenticateAsync would return a token but you would need accesstoken for various requests to be made. Let us see how to get the access token

function callbackOnError(err) {

function callBackOnSuccess(result) {

var token = result.responseData;
var CODE = returnedToken.substring(13);
var responseUrl = "";
var data = { "code": CODE, "redirect_uri": REDIRECT, "client_id": CLIENTID, "client_secret": CLIENT_SECRET, "scope": "", "grant_type": GRANT_TYPE };

var postUrl = 'client_id=' + encodeURIComponent(CLIENTID) + '&redirect_uri=' + encodeURIComponent(REDIRECT) + '&code=' + encodeURIComponent(CODE) + '&grant_type=authorization_code' + '&client_secret=' + encodeURIComponent(CLIENT_SECRET);

var obj = JSON.stringify(data);

type: "POST",
url: "",
headers: { "Content-type": "application/x-www-form-urlencoded" },
data: postUrl,
responseType: "json"
}).done(onSuccess, onError, onProgress);

function onSuccess(result) {
var response = JSON.parse(result.response);
var accessToken = encodeURIComponent(response.access_token);

function onError(result) {

function onProgress(result) {

Now the accessToken thus received in OnSuccess method is the token you can use with your requests to get data. For example ,

function getUserInfo()
        type: "GET",
        url: "" + accesstoken , // recieved earlier
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        data: null,
        responseType: "jsonp"
function completed(response) {
    var user = response.response;
    var userObject = JSON.parse(user);

By Kyurius    Popularity  (2545 Views)