Using Cognito with PhoneGap/Cordova - Part 2


Facebook Sign in with OpenFB

back to Part 1
Code for tutorial is at Github Gist



 has created a excellent lightweight library for Facebook integration with Cordova/PhoneGap. Download it fromhttps://github.com/ccoenraets/OpenFB .
After you have downloaded OpenFB, create a template PhoneGap Build application and put logoutcallback.html and oauthcallback.html in the root folder withindex.html.
Create a folder called js and put openfb.js in it.
In order to improve the way OpenFB works with PhoneGap/Cordova we need to make a couple of changes. OpenFB uses the deviceready event to identify whether the app is using PhoneGap/Cordova. For reliability I prefer to pass this directly to OpenFB on initialisation. Also the address bar is not used when the inappbrowser is opened. This means if anything goes wrong the user is presented with a blank white screen.
Open in your editor openfb.js and add a cordova parameter to the init function:


    /**
     * Initialize the OpenFB module. You must use this function and initialize the module with an appId before you can
     * use any other function.
     * @param params - init paramters
     *  appId: The id of the Facebook app,
     *  tokenStore: The store used to save the Facebook token. Optional. If not provided, we use sessionStorage.
     */
    function init(params) {
        if (params.appId) {
            fbAppId = params.appId;
            if (params.cordova!=null){
                runningInCordova = params.cordova;
            }
        } else {
            throw 'appId parameter not set in init()';
        }

        if (params.tokenStore) {
            tokenStore = params.tokenStore;
        }
    }

Also change all window.open calls to 'location=yes';


Now open your config.xml file and add the inappbrowser plugin.



    AWS Cognito Example App

    
        Example app using AWS Cognito 
    

    
        Paul Coady
    

    
    

Now lets create a simple index.html page with our login buttons and status output. This will load Jquery and the AWS Javascript SDK.

  
    AWS Cognito App
    
     
  
  
        
        
        

Next create a file app.js in the js folder. Create a self-invoking anonymous function to contain our code.
(function($){


 
})(jQuery); 
Add variables in app.js:
AWS_ACCOUNT_ID - This is your AWS account number.
COGNITO_IDENTITY_POOL_ID - You can get this from your Cognito dashboard by selecting Edit Identity Pool
IAM_ROLE_ARN - This is the IAM role created when you created your Cognito pool. You can get this from the the main Services menu - IAM - Roles - then select the role for your identity pool.
FACEBOOK_APP_ID - From the facebook app page.
var AWS_ACCOUNT_ID = 'XXXXXXXX';
var AWS_REGION = 'us-east-1';
var COGNITO_IDENTITY_POOL_ID = 'us-east-1:XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX';
var COGNITO_IDENTITY_ID, COGNITO_SYNC_TOKEN, AWS_TEMP_CREDENTIALS; 
var cognitosync;
var IAM_ROLE_ARN = 'arn:aws:iam::XXXXXXXXX:role/Cognito_CognitoBrowserExampleAuth_DefaultRole';
var COGNITO_SYNC_COUNT;
var COGNITO_DATASET_NAME = 'TEST_DATASET';
var FACEBOOK_APP_ID = 'XXXXXXXXXXXXXX';
var FACEBOOK_TOKEN;
var FACEBOOK_USER = {
  id: '',
  first_name: '',
  gender: '',
  last_name: '',
  link: '',
  locale: '',
  name: '',
  timezone: 0,
  updated_time: '',
  verified: false 
};
var userLoggedIn = false;

var message = 'AWS Cognito Example App Loaded_____';
var errorMessage = '';

Now add some code for our button events and clearing our status areas.
function clearConsole(){
    message = "";
    $('#appConsole').html(message);
    errorMessage = "";
    $('#errorConsole').html(errorMessage);    
}

// Login button
$('#btnLogin').on('click', function (event) {
    login();
});

// Login button
$('#btnLogout').on('click', function (event) {
    logout();
});
Now lets add our call to OpenFB.init and functions for handling login, logout, revoke permissions (not used here) and getting user info. I won't go into much detail here as this is explained on the OpenFB Github. There is a call to a function getCognitoID() in the callback of getInfo() below, please comment this out for now as we will be building this later.
openFB.init({
    appId:FACEBOOK_APP_ID, 
    cordova:true
});

function login() {
    clearConsole();        
    openFB.login(
        function(response) {
            if(response.status === 'connected') {
                FACEBOOK_TOKEN = response.authResponse.token;
                message += "Connected to Facebook_____";
                $('#appConsole').text(message);
                getInfo();
            } else {
                errorMessage += 'Facebook login failed: ' + response.error + "_____";
                $('#errorConsole').text(errorMessage);
            }
        }, {scope: 'email,read_stream,publish_stream'});
}

function getInfo() {
    openFB.api({
        path: '/me',
        success: function(data) {            
            message += "Logged in with Facebook as " + data.name+"_____";
            $('#appConsole').text(message);
            getCognitoID();
        },
        error: errorHandler});
}

function logout() {
    openFB.logout(
        function() {
            message += "Logged out of Facebook_____";
            $('#appConsole').text(message);
        },
        errorHandler);
}

function revoke() {
    openFB.revokePermissions(
        function() {
            message += "Permissions revoked_____";
            $('#appConsole').text(message);                
        },
        errorHandler);
}

function errorHandler(error) {
    errorMessage += error.message;
    $('#errorConsole').text(errorMessage);
}

Now you can build and run your app. You should be able to login to Facebook.


Now that we have our Facebook session token we will use this in the next page to get our Cognito ID credentials.

Get CognitoID Credentials

Now it's time to pass our Facebook token over to Cognito. Prior to version v2.0.14 of the AWS Javascript SDK this was a difficult process involving calls to IAM and STS. A new object CognitoIdentityCredentials has greatly simplified the CognitoID credentials process by removing the need to create STS tokens and temporary IAM credentials yourself.
We are going to create a new function to get our CognitoID credentials. Open app.js in your editor and add a call to the new function getCognitoID() in the success callback of our getInfo page.
function getInfo() {
    openFB.api({
        path: '/me',
        success: function(data) {            
            message += "Logged in with Facebook as " + data.name+"_____";
            $('#appConsole').text(message);
            getCognitoID();
        },
        error: errorHandler});
}
Now lets create the function. There is a call to a function getCognitoSynToken() in the callback of AWS.config.credentials.get() below, please comment this out for now as we will be building this later.

function getCognitoID(){
  // The parameters required to intialize the Cognito Credentials object.
  var params = {
    AccountId: AWS_ACCOUNT_ID, // required
    RoleArn: IAM_ROLE_ARN,  // required
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, // required
    Logins: {
      'graph.facebook.com': FACEBOOK_TOKEN
    }  
  };   
  // set the Amazon Cognito region
  AWS.config.region = AWS_REGION;
  // initialize the Credentials object with our parameters
  AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);

  // We can set the get method of the Credentials object to retrieve
  // the unique identifier for the end user (identityId) once the provider
  // has refreshed itself
  AWS.config.credentials.get(function(err) {
    if (err){ // an error occurred
        errorMessage += "credentials.get: " + err, err.stack + "_____";
        $('#errorConsole').text(errorMessage);
        errorMessage += "AWS.config.credentials: " + JSON.stringify(AWS.config.credentials) + "_____";
        $('#errorConsole').text(errorMessage);
    }
    else{
      AWS_TEMP_CREDENTIALS = AWS.config.credentials;
      COGNITO_IDENTITY_ID = AWS.config.credentials.identityId;
      message += "Cognito Identity Id: " + COGNITO_IDENTITY_ID + "_____";
      $('#appConsole').text(message);  
      getCognitoSynToken();     
    }
  });
}

Now you can build and run your app. You should be able to login to Facebook and get your user Cognito ID.
Now that we have our Cognito ID credentials we can use this in the next page to get our CognitoSync Session Token.

Get CognitoSync Session Token

Now that we have our CognitoID credentials we can use these to access CognitoSync. First we need to use our new temporary credentials to create a CognitoSync session token.
We are going to create a new function to get our CognitoSync session token. Open app.js in your editor and add a call to the new function getCognitoSynToken() in the callback of getCognitoID().
function getCognitoID(){
  // The parameters required to intialize the Cognito Credentials object.
  var params = {
    AccountId: AWS_ACCOUNT_ID, // required
    RoleArn: IAM_ROLE_ARN,  // required
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, // required
    Logins: {
      'graph.facebook.com': FACEBOOK_TOKEN
    }  
  };   
  // set the Amazon Cognito region
  AWS.config.region = AWS_REGION;
  // initialize the Credentials object with our parameters
  AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);

  // We can set the get method of the Credentials object to retrieve
  // the unique identifier for the end user (identityId) once the provider
  // has refreshed itself
  AWS.config.credentials.get(function(err) {
    if (err){ // an error occurred
        errorMessage += "credentials.get: " + err, err.stack + "_____";
        $('#errorConsole').text(errorMessage);
        errorMessage += "AWS.config.credentials: " + JSON.stringify(AWS.config.credentials) + "_____";
        $('#errorConsole').text(errorMessage);
    }
    else{
      AWS_TEMP_CREDENTIALS = AWS.config.credentials;
      COGNITO_IDENTITY_ID = AWS.config.credentials.identityId;
      message += "Cognito Identity Id: " + COGNITO_IDENTITY_ID + "_____";
      $('#appConsole').text(message);  
      getCognitoSynToken();     
    }
  });
}
In order to get the token we must make a call to listRecords. If our dataset doesn't exist (as is the case now) it will be created automatically. We also get the sync count for the dataset which is needed later to add or change dataset records. There is a call to a function addRecord() in the callback of cognitosync.listRecords() below, please comment this out for now as we will be building this later.

function getCognitoSynToken(){
  // Other AWS SDKs will automatically use the Cognito Credentials provider
  // configured in the JavaScript SDK.
  cognitosync = new AWS.CognitoSync();
  cognitosync.listRecords({
    DatasetName: COGNITO_DATASET_NAME, // required
    IdentityId: COGNITO_IDENTITY_ID,  // required
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID  // required
  }, function(err, data) {
    if (err){
      errorMessage += "listRecords: " + err, err.stack + "_____";
      $('#errorConsole').text(errorMessage); // an error occurred       
    }
    else {
      COGNITO_SYNC_TOKEN = data.SyncSessionToken;
      COGNITO_SYNC_COUNT = data.DatasetSyncCount;
      message += "listRecords: " + JSON.stringify(data) + "_____"; 
      message += "DatasetSyncCount: " + COGNITO_SYNC_COUNT + "_____";      
      $('#appConsole').text(message);       // successful response
      addRecord();         
    }
  });
}

Now you can build and run your app. You should be able to login to Facebook, create a dataset and list the records.
Now that we have our CognitoSync Session Token we can use this in the next part 3 to access the CognitoSync database and add records to the dataset.
BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Using Cognito with PhoneGap/Cordova - Part 1




The potential for really powerful mobile applications is huge when Cognito is used to combine the power of AWS with your PhoneGap/Cordova application. It is also a great low cost alternative to Parse.com when used for storing user information.
This tutorial will focus on using Cognito with the AWS Javascript SDK for Browser along with the excellent OpenFB library developed by  to simplify token creation. The sample app will be created for the Adobe PhoneGap Build process. This could be used with apps that access files on an S3 bucket and also require user information to be stored. I have chosen Facebook as the identity provider but a similar process applies for Amazon and Google. I would recommend only using one identity provider for your app so that your users don't produce multiple Cognito key stores.
With the release of v2.0.14 of the AWS Javascript SDK, a new object CognitoIdentityCredentials has greatly simplified the CognitoID credentials process by removing the need to create STS tokens and temporary IAM credentials. The simplified process to create a Cognito session is as follows:


Code for tutorial is at Github Gist

Register a Facebook App


This process is different to that used with NodeJS because the app will be running from the device local domain.
Go to developers.facebook.com and select Apps - Create a New App

Record your App ID and App Secret somewhere safe, we will need it later.
Click on Settings then click on Advanced (do not fill in app domain details or add platform).
Select Native or Desktop app.


Add https://www.facebook.com/connect/login_success.html as the Valid OAuth redirect URI.


Enter your contact email and Save Changes
Next select Status and Review
Toggle Yes for Do you want to make this app and all its live features available to the general public?

Now that we have registered our new app with Facebook, we will tell Cognito all about it next.

Create a Cognito Pool


Now that we have a Facebook App registered we need to create a Cognito pool that will be linked to the Facebook app.
Go to the Cognito start page and click Get Started Now




Step 1:
Give your app a name in Identity Pool Name.
Paste your Facebook App ID.
Leave Enable Access to Unauthenticated Identities unchecked.
Click Create Pool
Step 2:
An IAM role has been automatically created for you. Click Update Roles
Step 3:
Example code for native mobile apps has been created for you which is useless for us with javascript so just click Done.


Finished! You have created a Cognito pool and are viewing its dashboard. Next, in part 2 we will use OpenFB to sign in and get our Facebook session token.
BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Multiple Subnets per Availability Zone with Auto Scaling groups


You can now select more than one subnet per availability zone in an Autoscaling group.
You no longer need to remove an existing subnet from an Autoscaling group in order to reconfigure the subnets. You can simply add more subnets without affecting your applications availability.

More details in the docs at:
AutoScaling Developer Guide

BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

New 16 TB and 20,000 IOPS EBS Volumes


AWS have now made available Provisioned IOPS (SSD) volumes with up to 16 TB and 20,000 IOPS and a maximum throughput of 320 MBps.


Before you would need to attach 16 x 1 TB 1250 IOPS volumes to achieve the same performance.


General Purpose (SSD) volumes are also now available with up to 16 TB and 10,000 IOPS and a maximum throughput of 160 MBps.

General Purpose (SSD) volumes are also now designed to deliver a consistent baseline performance of 3 IOPS/GB to a maximum of 10,000 IOPS, and provide up to 160 MBps of throughput per volume.

More information in the docs:
Amazon EBS Product Details
EC2 User Guide




BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Cross-Region Replication for Amazon S3


To  provide 99.999999999% durability, AWS S3 has always had a high degree of replication. In the past, the location of that replicated data has been a mystery to the account holder. This has made it difficult for those that, as part of their organization's compliance, require that data be in totally different geographical locations.
With the release today of Cross-Region Replication for AWS S3, you can now specify the region and bucket location in that region to replicate data to. The process is extremely easy and straightforward.

There are requirements though:

  • The source and destination buckets must be versioning-enabled.
  • You can replicate from a source bucket to only one destination bucket.
  • An IAM role must be created to grant permissions for S3 actions on the buckets.
  • If the source bucket owner is not the owner of the destination bucket then you must have permissions for the S3 actions.

More detailed information in the docs at:
Amazon Simple Storage Service - Developer Guide - Cross-Region Replication



BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Using AWS Cognito with Node.JS - Part 3


Add Records to the CognitoSync Dataset

back to Part 2

The complete code for the tutorial is at GitHub.

Now that we have our CognitoSync session token we can use this to add, modify or delete CognitoSync dataset records.
To demonstrate we are going to call addRecord to add a record. Open index.js in your editor and add a call to the addRecord in the callback of getCognitoSynToken().
 function getCognitoSynToken(){
  /* Other AWS SDKs will automatically use the Cognito Credentials provider */
  /* configured in the JavaScript SDK. */
  cognitosync = new AWS.CognitoSync();
  cognitosync.listRecords({
    DatasetName: COGNITO_DATASET_NAME, /* required */
    IdentityId: COGNITO_IDENTITY_ID,  /* required */
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID  /* required */
  }, function(err, data) {
    if (err) console.log("listRecords: ".red + err, err.stack); /* an error occurred */
      else {
        console.log("listRecords: ".green + JSON.stringify(data));
        COGNITO_SYNC_TOKEN = data.SyncSessionToken;
        COGNITO_SYNC_COUNT = data.DatasetSyncCount;
        console.log("SyncSessionToken: ".green + COGNITO_SYNC_TOKEN);           /* successful response */
        console.log("DatasetSyncCount: ".green + COGNITO_SYNC_COUNT);
        addRecord();     
      }
  });
}
Now lets add a record user_id that stores the users facebook id. We need to not only pass the CognitoSync session token but also the syncount that we got from the call to listRecords.
 function addRecord(){
  var params = {
    DatasetName: COGNITO_DATASET_NAME, /* required */
    IdentityId: COGNITO_IDENTITY_ID, /* required */
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, /* required */
    SyncSessionToken: COGNITO_SYNC_TOKEN, /* required */
    RecordPatches: [
      {
        Key: 'USER_ID', /* required */
        Op: 'replace', /* required */
        SyncCount: COGNITO_SYNC_COUNT, /* required */
        Value: FACEBOOK_USER.id
      }
    ]
  };
  console.log("UserID: ".cyan + FACEBOOK_USER.id);
  cognitosync.updateRecords(params, function(err, data) {
    if (err) console.log("updateRecords: ".red + err, err.stack); /* an error occurred */
    else     console.log("Value: ".green + JSON.stringify(data));           /* successful response */
  });
}
Now run the app with npm start again and you should get something like the following from the console after you have logged in from the browser.
GET / 304 318ms
GET / 200 17ms - 338b
GET /stylesheets/style.css 304 2ms
GET /auth/facebook 302 4ms - 388b
GET /auth/facebook/callback?code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 302 348ms - 72b
FACEBOOK_TOKEN:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GET /success 304 17ms
Cognito Identity Id: us-east-1:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
listRecords: {"Count":1,"DatasetDeletedAfterRequestedSyncCount":false,"DatasetExists":true,"DatasetSyncCount":1,"LastModifiedBy":"XXXXXXXXXXXX","Records":[{"DeviceLastModifiedDate":"2014-08-15T15:33:58.627Z","Key":"USER_ID","LastModifiedBy":"XXXXXXXXXX","LastModifiedDate":"2014-08-15T15:33:58.627Z","SyncCount":1,"Value":"XXXXXXXXXXXX"}],"SyncSessionToken":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}
SyncSessionToken: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DatasetSyncCount: 1
UserID: 524972310968618
Value: {"Records":[{"Key":"USER_ID","SyncCount":2,"Value":"XXXXXXXXXXXXXXX"}]}

Finished! We have logged in with Facebook, created a dataset and added a record to it. Stay tuned for more AWS development tutorials.
Like coding? AWS Certified Developers are in HOT demand! Check out BackSpace Academy for more details.
BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Amazon CloudFront Signed HTTP Cookies


Previously restricting access to CloudFront involved using signed URLs. Now another option is available through the use of signed HTTP cookies.This has the advantage of allowing restricted access to multiple objects or to a whole site. An example process for transcoded media files in an S3 bucket is as follows:


If you are sitting an AWS make sure you remember that there are now two ways of securing access to CloudFront objects; signed URLs and signed HTTP cookies.
More information at: Serving Private Content through CloudFront
BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Using AWS Cognito with Node.JS - Part 2


Facebook Sign in with Passport

back to Part 1
The complete code for the tutorial is at GitHub.

Set up node.js on a US-East region Amazon Linux EC2 instance and configure firewall settings for HTTP access.
On your EC2 instance create a new app using the express generator.
$ express CognitoExample
$ cd CognitoExample
$ npm install

Do npm start and check your browser that you see the default Express page OK.
Install Passport, Passport-Facebook, the AWS javascript SDK and colors (for multi colored console output). Use --save to add to the package.json file.
$ npm install passport --save
$ npm install passport-facebook --save

$ npm install aws-sdk --save
$ npm install colors --save

Open in your editor www from the bin folder and change port to 8080.
Open in your editor index.jade from the views folder and change the Express sample page to a Facebook login page:
p Please log in. We  only have access to your name and facebook id number. We do not collect  sensitive information such as email addresses.
a(href='/auth/facebook') Sign in with Facebook

Open in your editor index.js from the routes folder and add:
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var AWS = require('aws-sdk');
var colors = require('colors');

Next add variables:
AWS_ACCOUNT_ID - This is your AWS account number.
COGNITO_IDENTITY_POOL_ID - You can get this from your Cognito dashboard by selecting Edit Identity Pool
IAM_ROLE_ARN - This is the IAM role created when you created your Cognito pool. You can get this from the the main Services menu - IAM - Roles - then select the role for your identity pool.
FACEBOOK_APP_ID and FACEBOOK_APP_SECRET - From the facebook app page.

var AWS_ACCOUNT_ID = 'XXXXXXXX';
var AWS_Region = 'us-east-1';
var COGNITO_IDENTITY_POOL_ID = 'us-east-XXXXXXXXXXXXXXXXXXX';
var COGNITO_IDENTITY_ID, COGNITO_SYNC_TOKEN, AWS_TEMP_CREDENTIALS;
var cognitosync;
var IAM_ROLE_ARN = 'arn:aws:iam::XXXXXXXXX:role/Cognito_AWSCognitoTutorialAuth_DefaultRole';
var COGNITO_SYNC_COUNT;
var COGNITO_DATASET_NAME = 'TEST_DATASET';
var FACEBOOK_APP_ID = 'XXXXXXXXXXXX';
var FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
var FACEBOOK_TOKEN;
var FACEBOOK_USER = {
  id: '',
  first_name: '',
  gender: '',
  last_name: '',
  link: '',
  locale: '',
  name: '',
  timezone: 0,
  updated_time: '',
  verified: false
};
var userLoggedIn = false;
var cognitoidentity = new AWS.CognitoIdentity();
Now let's add our code for Passport to collect the Facebook token:
router.use(passport.initialize());
router.use(passport.session());

passport.use(new FacebookStrategy({
  clientID: FACEBOOK_APP_ID,
  clientSecret: FACEBOOK_APP_SECRET,
  callbackURL: 'http://dev.ap-robotics.com/auth/facebook/callback'
}, function(accessToken, refreshToken, profile, done) {
  process.nextTick(function() {
    FACEBOOK_TOKEN = accessToken; 
    FACEBOOK_USER = profile._json;
    userLoggedIn = true;
    done(null, profile);
  });
}));

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});
Now lets add our success and error callbacks:
/* GET Facebook page. */
router.get('/auth/facebook', passport.authenticate('facebook'));

/* GET Facebook callback page. */
router.get('/auth/facebook/callback', passport.authenticate('facebook', {
  successRedirect: '/success',
  failureRedirect: '/error'
}));

/* GET Facebook success page. */
router.get('/success', function(req, res, next) {
  console.log('FACEBOOK_TOKEN:'.green + FACEBOOK_TOKEN); 
  res.send('Logged in as ' + FACEBOOK_USER.name + ' (id:' + FACEBOOK_USER.id + ').');
});

/* GET Facebook error page. */
router.get('/error', function(req, res, next) {
  res.send("Unable to access Facebook servers. Please check internet connection or try again later.");
});

Now run the app with npm start and you should get the success page after you have logged in from the browser.:
Logged in as Paul Coady (id:XXXXXXXXXXXXXX).
The console output should be something like:
GET / 200 395ms - 338b
GET / 200 18ms - 338b
GET /stylesheets/style.css 200 5ms - 110b
GET /auth/facebook 302 4ms - 388b
GET /auth/facebook/callback?code=AQD4e7zDMnHkQxtEO-XXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXX 302 347ms - 72b
FACEBOOK_TOKEN:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GET /success 304 2ms
Now that you have your Facebook token you can now use it to get the CognitoID credentials.

Get CognitoID Credentials


Now it's time to pass our Facebook token over to Cognito. Prior to version v2.0.14 of the AWS Javascript SDK this was a difficult process involving calls to IAM and STS. A new object CognitoIdentityCredentials has greatly simplified the CognitoID credentials process by removing the need to create STS tokens and temporary IAM credentials yourself.
We are going to create a new function to get our CognitoID credentials. Open index.js in your editor and add a call to the new function getCognitoID() in the callback of our success page.
 /* GET Facebook success page. */
router.get('/success', function(req, res, next) {
  console.log('FACEBOOK_TOKEN:'.green + FACEBOOK_TOKEN); 
  getCognitoID();
  res.send('Logged in as ' + FACEBOOK_USER.name + ' (id:' + FACEBOOK_USER.id + ').');
});
Now lets create the function:
 function getCognitoID(){
  var params = {
    AccountId: AWS_ACCOUNT_ID, /* required */
    RoleArn: IAM_ROLE_ARN,  /* required */
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, /* required */
    Logins: {
      'graph.facebook.com': FACEBOOK_TOKEN
    } 
  };
  AWS.config.region = AWS_Region;
  /* initialize the Credentials object */
  AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);
  /* Get the credentials for our user */
  AWS.config.credentials.get(function(err) {
    if (err) console.log("credentials.get: ".red + err, err.stack); /* an error occurred */
      else{
&nbsp &nbsp &nbsp &nbsp AWS_TEMP_CREDENTIALS = AWS.config.credentials.data.Credentials;
        COGNITO_IDENTITY_ID = AWS.config.credentials.identityId;
        console.log("Cognito Identity Id: ".green + COGNITO_IDENTITY_ID);
      }
  });
}
Now run the app with npm start again and you should get something like the following from the console after you have logged in from the browser.
GET / 304 322ms
GET /stylesheets/style.css 304 3ms
GET /auth/facebook 302 4ms - 388b
GET /auth/facebook/callback?code=XXXXXXXXXXXXXX_-XXXXXXXXX-XXXXXXXXXXXXX_XXXXXXXXXXXXXXXXX_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXX_XXXXXXXXXX_XXX--XXX-XXXXXXXXXXX-XXXXX-XXXXX_XXXXXXXXXXXXXXX-XXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX 302 327ms - 72b
FACEBOOK_TOKEN:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GET /success 304 36ms
Cognito Identity Id: us-east-1:XXXXXXX-XXXX-XXX-XXX-XXXXXXXX
Now that we have our CognetoID credentials we can get our CognetoSync session token.

Get CognitoSync Session Token


Now that we have our CognitoID credentials we can use these to access CognitoSync. First we need to use our new temporary credentials to create a CognitoSync session token.
We are going to create a new function to get our CognitoSync session token. Open index.js in your editor and add a call to the new function getCognitoSynToken() in the callback of getCognitoID().
 function getCognitoID(){
  var params = {
    AccountId: AWS_ACCOUNT_ID, /* required */
    RoleArn: IAM_ROLE_ARN,  /* required */
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID, /* required */
    Logins: {
      'graph.facebook.com': FACEBOOK_TOKEN
    } 
  };
  AWS.config.region = AWS_Region;
  /* initialize the Credentials object */
  AWS.config.credentials = new AWS.CognitoIdentityCredentials(params);
  /* Get the credentials for our user */
  AWS.config.credentials.get(function(err) {
    if (err) console.log("credentials.get: ".red + err, err.stack); /* an error occurred */
      else{
&nbsp &nbsp &nbsp &nbsp AWS_TEMP_CREDENTIALS = AWS.config.credentials.data.Credentials;
        COGNITO_IDENTITY_ID = AWS.config.credentials.identityId;
        console.log("Cognito Identity Id: ".green + COGNITO_IDENTITY_ID);
        getCognitoSynToken();
      }
  });
}
In order to get the token we must make a call to list records. If our dataset doesn't exist (as is the case now) it will be created automatically. We also get the sync count for the dataset which is needed later to add or change dataset records.
Now lets create the function:
 function getCognitoSynToken(){
  /* Other AWS SDKs will automatically use the Cognito Credentials provider */
  /* configured in the JavaScript SDK. */
  cognitosync = new AWS.CognitoSync();
  cognitosync.listRecords({
    DatasetName: COGNITO_DATASET_NAME, /* required */
    IdentityId: COGNITO_IDENTITY_ID,  /* required */
    IdentityPoolId: COGNITO_IDENTITY_POOL_ID  /* required */
  }, function(err, data) {
    if (err) console.log("listRecords: ".red + err, err.stack); /* an error occurred */
      else {
        console.log("listRecords: ".green + JSON.stringify(data));
        COGNITO_SYNC_TOKEN = data.SyncSessionToken;
        COGNITO_SYNC_COUNT = data.DatasetSyncCount;
        console.log("SyncSessionToken: ".green + COGNITO_SYNC_TOKEN);           /* successful response */
        console.log("DatasetSyncCount: ".green + COGNITO_SYNC_COUNT);
      }
  });
}
Now run the app with npm start again and you should get something like the following from the console after you have logged in from the browser.
GET / 304 318ms
GET / 200 17ms - 338b
GET /stylesheets/style.css 304 2ms
GET /auth/facebook 302 4ms - 388b
GET /auth/facebook/callback?code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 302 348ms - 72b
FACEBOOK_TOKEN:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
GET /success 304 17ms
Cognito Identity Id: us-east-1:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
listRecords: {"Count":1,"DatasetDeletedAfterRequestedSyncCount":false,"DatasetExists":true,"DatasetSyncCount":1,"LastModifiedBy":"XXXXXXXXXXXX","Records":[{"DeviceLastModifiedDate":"2014-08-15T15:33:58.627Z","Key":"USER_ID","LastModifiedBy":"XXXXXXXXXX","LastModifiedDate":"2014-08-15T15:33:58.627Z","SyncCount":1,"Value":"XXXXXXXXXXXX"}],"SyncSessionToken":"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}
SyncSessionToken: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DatasetSyncCount: 1

Ok...Now that we have our CognetoSync session token we can use this to do something useful like add records to our dataset or download a file.
In Part3 we will finish off with some examples of using Cognito to access AWS resources.
BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.

Using AWS Cognito with Node.JS - Part 1




This tutorial will focus on using Cognito with the AWS Javascript SDK for Node.js along with the Node Passport module to simplify token creation. This could be used with apps that access files on a server or S3 bucket and also require user information to be stored. I have chosen Facebook as the identity provider but a similar process applies for Amazon and Google. I would recommend only using one identity provider for your app so that your users don't produce multiple Cognito key stores.
With the release of v2.0.14 of the AWS Javascript SDK, a new object CognitoIdentityCredentials has greatly simplified the CognitoID credentials process by removing the need to create STS tokens and temporary IAM credentials. The simplified process to create a Cognito session is as follows:




Assumptions. You know the following:
1. How to set up Node on an EC2 instance.
2. Can configure firewall settings on EC2.
3. Experienced with Node and Express.

The complete code for the tutorial is at GitHub.

Register a Facebook App


Go to developers.facebook.com and select Apps - Create a New App

Record your App ID and App Secret somewhere safe, we will need it later.
Click on Settings then click on Add Platform

Select Website
Site URL enter your site's Facebook callback page: http://yoursite.com/auth/facebook/callback
App Domains enter your site domain: http://yoursite.com
Enter your contact email and Save Changes
Next select Status and Review
Toggle Yes for Do you want to make this app and all its live features available to the general public?

Now that we have registered our new app with Facebook, we will tell Cognito all about it.

Create a Cognito Pool


Now that we have a Facebook App registered we need to create a Cognito pool that will be linked to the Facebook app.
Go to the Cognito start page and click Get Started Now


Step 1:
Give your app a name in Identity Pool Name.
Paste your Facebook App ID.
Leave Enable Access to Unauthenticated Identities unchecked.
Click Create Pool
Step 2:
An IAM role has been automatically created for you. Click Update Roles
Step 3:
Example code for native mobile apps has been created for you which is useless for us with javascript so just click Done.

Finished! You have created a Cognito pool and are viewing its dashboard.

In part 2 we will create a Node.JS application that connects to Cognito ID.
See you in Part 2!



BackSpace Academy CEO BackSpace Technology LLC

Providing the best value AWS certification courses and exam engines.