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 https://code.google.com/apis/console and as this is a desktop app , let the callback url be http://localhost

Now you have the following parameters with you

var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile'; // 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 = 'https://accounts.google.com/o/oauth2/auth?' +'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type= code';
var requestUri = new Windows.Foundation.Uri(requesturl);
var callbackUri = new Windows.Foundation.Uri("https://accounts.google.com/o/oauth2/approval?");

Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
Windows.Security.Authentication.Web.WebAuthenticationOptions.useTitle,
requestUri,
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) {
console.log(err.number);
}

function callBackOnSuccess(result) {

var token = result.responseData;
var CODE = returnedToken.substring(13);
var responseUrl = "https://accounts.google.com/o/oauth2/token";
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);

WinJS.xhr({
type: "POST",
url: "https://accounts.google.com/o/oauth2/token",
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) {
console.log("Error..!!");
}

function onProgress(result) {
console.log("Loading..!!");
}

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

function getUserInfo()
{
WinJS.xhr({
        type: "GET",
        url: "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accesstoken , // recieved earlier
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        data: null,
        responseType: "jsonp"
    }).done(
function completed(response) {
    var user = response.response;
    var userObject = JSON.parse(user);
    console.log(user);
});
}

By Kyurius    Popularity  (2422 Views)