Angular JS 1.x Security CSRF Protection

Defination: (Source:wiki)
Cross-site request forgery is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
(or)
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the website trusts.
Prevention methods:

  1. Check standard headers to verify the request from same origin or not
  2. Check CSRF token and it’s validity against to user session Id.

AngularJS will support by default to avoid CSRF attacks, we need to send XSRF-TOKEN into browsers cookie, then angular will automatically pick and append X-XSRF-TOKEN as a header.

Cookie info:

AngularJS with a general $http promise will prepare header with X-XSRF-TOKEN, if one of the domain cookies contains a token with XSRF-TOKEN key name.
If we want to change HTTP header key name, with custom  XSRF token we need to provide defaults.xsrfHeaderName so that angular will prepare with custom token key.
Please check below code snap from angularJS framework for better understanding of how it works:

var xsrfValue = urlIsSameOrigin(config.url) ?
     $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
     : undefined;
if (xsrfValue) {
  reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}

And check out this working example, inspect HTTP headers via developer tools.

 var app = angular.module('csrf_example', []);
 app.controller('MainCtrl', function($scope, $log, $http) {
 document.cookie = "XSRF-TOKEN=sjdjsdjsdbjhfg";
 $http.get('path').then(function() {
 console.log('Network call done!');
 });
 });

Promises/deferred objects – asynchronous computations

Definition: (ECMA-2015)
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
A Promise represents an operation that hasn’t completed yet, but is expected in the future, while it’s in execution. Promises are very useful for remote calls to overcome network latency, once network responded promise will resolve or reject based on returned data.
Promise Abstract Operations:
[table class=”table table-striped”]
Field Name,Value type,Meaning
[[Promise]], An object, An object that is usable as a promise.
[[Resolve]], A function object, The function that is used to resolve the given promise object.
[[Reject]], A function object, the function that is used to reject the given promise object.
[/table]
We are using angular 1.x $q service to illustrate promises. $q is a similar implementation of promises concept by Kris Kowal’s Q.js. we can generate a new instance of promise by calling $q.defer(), which is equals new Promise() in ES 6. Deferred object contains promise property which is responsible for callback function executions such as onFulfilled, onRejected and progressBack.
Flex frameworks Action Script 3.0 also have a similar implementation like Q.js as AsyncToken,AsyncResponder. The syntax looks like below

//Flex AsyncToken usage
var token:AsyncToken = service.send();
token.addResponder(new mx.rpc.Responder(result, fault));

The $q object:
[table class=”table table-striped”]
Method Name,Meaning
$q. defer(),new instance of promise will returns a deferred object
$q.all(ArrayOfPromises),Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
[/table]
The Deferred object:
$q.defer() will returns a deferred object, which have below methods:
[table class=”table table-striped”]
Method Name,Meaning
deferred.resolve(value),resolves the derived promise with the value.
deferred.reject(reason),rejects the derived promise with the reason.
deferred.notify(value),provides updates on the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.
deferred.promise{}, An object that is usable as a promise
[/table]
The Promise object:
[table class=”table table-striped”]
Method Name,Meaning
then:function(onFulfilled, onRejected, progressBack)“, “it will hook result,fault and progress methods to a promise. then calls one of the callback methods asynchronously as soon as the result is available.”
catch(errorCallback), “shorthand for promise.then(null, errorCallback).one more way to provide fault method.”
[/table]
Below example will illustrate promises usage,

//$q for promises
//create module
var myApp = angular.module("promisesApp",[]);
//get $q as global Q for better and simple analysis
angular.injector(['ng', 'promisesApp']).invoke(function ($q) {window.Q = $q;});
//promisesApp.controller("promisCtrl",["$q",function(Q){
function result(response){
 console.log("Resolved and Response is:"+response);
 }
function fault(reason){
 console.log("Rejected and Error info: "+reason);
 }
function notify(update){
 console.log("Notification: "+update);
 }
function asyncExecution(resultObj,isResolvable,atTime){
 var defered = Q.defer();
 var promise = defered.promise;
 //Simulating network latency
 setTimeout(function(isResolvable){
 if(isResolvable){
 defered.notify('resolving now...');
 defered.resolve(resultObj);
 defered.notify('resolved');//notify Never prints, once promise resolved or rejects
 }
 else{
 defered.notify('rejecting now...');
 defered.reject("Got an Error");
 defered.notify('rejected');//notify Never prints, once promise resolved or rejects
 }
 },atTime,isResolvable);
 return promise;
}
var p1 = asyncExecution('p1',true,2000);
p1.then(result,fault,notify);
var p2 = asyncExecution('p2',false,3000);
p2.then(result,fault,notify);
var p3 = asyncExecution('p3',true,4000);
p3.then(result,fault,notify);

Output as following:

Notification: resolving now...
Resolved and Response is:p1
Notification: rejecting now...
Rejected and Error info: Got an Error
Notification: resolving now...
Resolved and Response is:p3

Promises Chaining:
Chaining is useful when we need to make synchronous calls to server. always promises will look for failure handler, if not present in current then-able it will look for next available then-able. chaining will continue only if a success handler on returning a promise object.  below example will explain about chaining of multiple promises.

//Chaining
var p1 = asyncExecution('p1',true,2000);
var p2 = asyncExecution('p2',true,3000);
var p3 = asyncExecution('p3',true,4000);
//promises will look for failure handler, if not present
//in current then-able it will look for next available then-able
p1.then(function(a){result(a);return p2})
//return Promise to continue chaining
.then(function(a){result(a);return p3})
.then(result);

Output as following:

Resolved and Response is:p1
Resolved and Response is:p2
Resolved and Response is:p3

Combine Multiple promises as one promise:

//let combin and know all promises are done or not
var p1 = asyncExecution('p1',true,2000);
var p2 = asyncExecution('p2',true,3000);
var p3 = asyncExecution('p3',true,4000);
Q.all([p1,p2,p3])
.then(function(){console.log('All Async tasks done')},
     function(){console.log('Failed:Soming worng!!')})
.finally(function(){
     console.log('Finally: I will execute any way')});

Output as following:

All Async tasks done
Finally: I will execute any way

Directives scope in AngularJS

Scope is context where the model is stored so that controllers, directives and expressions can access it. By default, each directive inherits its parent’s scope, which is passed to it in the link function. below three options are described scope creation in angularjs,

Scope:false (default) which basically tells AngularJS that the directive scope is the same as the parent scope.
Example: If scope:false means it will simply return same address location of parent scope.
working Fiddle.

return {
    restrict: 'A',
      scope:false,
    template: '',
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + " + directive postfix";
        child = scope;
    }

Result:

 image01

Scope:true creates new scope object but never override parent properties. The directive thus gets access to all the variables and functions from the parent scope, but any modifications it makes are not available in the parent.
Example: create a child scope prototypically inherited with scope: true.
working Fiddle.

return {
    restrict: ‘A’,
      scope:true,
    template: ”,
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + ” + directive postfix”;
        child = scope;
    }

Result:

image00

Scope:{} (isolated scope) This scope does not inherit anything from the parent, and any data that the parent scope needs to share with this directive needs to be passed in through HTML attributes
Example: create an isolated scope with scope: {} then you can bind some property to parent scopes with ‘@’, ‘&’, ‘=’.
working Fiddle.

return {
    restrict: ‘A’,
      scope:{},
    template: ”,
    link: function(scope, element, attrs) {
        console.log(scope);
        scope.data = scope.data + ” + directive postfix”;
        child = scope;
    }

Result:

image02