Category Archives: JavaScript

AngularJS basics

I’ve been reading a great introductory book on AngularJS recently (authored by Brad Green and Shyam Seshadri) and thought i’ll share with you some of my notes (prior to going further with reading however, i strongly advise to watch few videos on the subject from the wonderful website):

  • The role of the server:
    • Traditional Web Apps – create HTML pages by assembling components (header, content, footer, etc.), joining it with the data and then shipping it all over the wire to the browser to display.
    • AngularJS Apps – serve static resources (HTML templates, media, etc.) and data to the browser which takes care of assembling.
  • “By structuring your application with Angular, your application’s templates are kept separate from the data that populates them. The result of this is that these templates are cacheable. Only new data need to come down to the browser after the first load. Just as with JavaScript, images, CSS, and other resources, caching these templates can give your application even better performance.”
  • Model-View-Controller (MVC)
    • application architecture that separates the code between:
      • model – managing data (which is stored in object properties)
      • controller – managing the application logic (javascript classes)
      • view – presenting the data to the user (DOM)
    • “The view gets data from the model to display to the user. When a user interacts with the application by clicking or typing, the controller responds by changing data in the model. Finally, the model notifies the view that a change has occurred so that it can update what it displays.”
  • Data binding
    • “…just declare which parts of the UI map to which JavaScript properties and have them sync automatically.”
    • use double-curly syntax {{someText}} or ng-bind=”someText” directive to insert new content into an existing HTML template (with the double-curly syntax, on the very first page load of your application’s index.html, there’s a chance that your user will see the un-rendered template before Angular has a chance to replace the curlies with your data).
  • Dependency Injection (definition taken from Craig Walls “Spring in Action” 3rd ed.)
    • Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to code which is:
      • highly coupled
      • hard-to-test
      • difficult to reuse
      • difficult to understand
      • code that  typically exhibits “whack-a-mole” bug behavior (fixing one bug results in the creation of one or more new bugs)
    • With DI, on the other hand, objects are given their dependencies at creation time by some third party (usually specialized DI framework) that coordinates each object in the system. Objects aren’t expected to create or obtain their dependencies—dependencies are injected into the objects that need them.
  • Directives:
    • in AngularJS you can write your templates as HTML, because at the core of the framework there is a powerful DOM transformation engine included that lets you extend HTML’s syntax (ng-app, ng-controller, ng-model and similar directives).
  • To invoke AngularJS you must:
    • Load the angular.js library (eg. from Google’s CDN (content delivery network), ie.:”)
    • Tell Angular which part of the DOM it should manage with the ng-app directive (eg. <html ng-app>)
  • Basic AngularJS app startup flow:
    • A user requests the first page of your application.
    • The user’s browser makes an HTTP connection to your server and loads the index.html page containing your template.
    • Angular loads into the page, waits for the page to be fully loaded, and then looks for ng-app to define its template boundaries.
    • Angular traverses the template and looks for directives and bindings. This results in registration of listeners and DOM manipulation, as well as fetching initial data from the server. The end result of this work is that the app is bootstrapped and the template is converted into view as a DOM.
    • You connect to your server to load additional data you need to show the user as needed.
  • Rationale behind writing “unobtrusive JavaScript” code (eg. not using click, mousedown, and other such inline event handlers in your HTML) and how AngularJS re-examine the problem:
    • Not everyone’s browser supports JavaScript. Let everyone see all of your content and use your app without needing to execute code in the browser.
      • this is no longer true as if you’re running a browser without JavaScript, you’re relegated to sites created in the ’90s
    • Some folks use browsers that work differently. Visually impaired folks who use screen-readers and some mobile phone users can’t use sites with JavaScript.
      • modern screen-readers have caught up. With proper use of ARIA semantic tags, you can make very rich UIs easily accessible. Mobile phones now run JavaScript on par with desktop machines.
    • Javascript works differently across different platforms. IE is usually the culprit here. You need to put in different event-handling code depending on the browser.
      • Angular has an equivalent in the form of ng-eventhandler=”expression” where eventhandler would be replaced by click, mousedown, change, and so on. AngularJS directives differ from their event handler predecessors in that they b

        ehave the same in every browser. Angular takes care of the differences for you.

    • These event handlers reference functions in the global namespace. It will cause you headaches when you try to integrate other libraries with functions of the same names.
      • Similarly to the previous point, AngularJS equivalent eventhandlers do not operate on the global namespace. The expressions you specify can only access functions and data that is in the scope of the element’s controller.
    • These event handlers combine structure and behavior. This makes your code more difficult to maintain, extend, and understand.
      • There’s a simple acid test we can use to figure out if our system suffers from this coupling: can we create a unit test for our app logic that doesn’t require the DOM to be present? In Angular, yes we can write controllers containing our business logic without having references to the DOM.
  • While angular is a client-side-only technology and it’s possible to create angular web apps that don’t require a back-end server at all, it is recommended to host the project files using a local web-server during development to avoid issues with security restrictions (sandbox) in browsers. The sandbox implementation varies between browsers, but quite often prevents things like cookies, xhr, etc to function properly when an html page is opened via file:// scheme instead of http://.

Producing JWT tokens

To produce the JWT token i’ll be using the Nimbus JOSE+JWT Java library, which implements the Javascript Object Signing and Encryption (JOSE) suite of specifications as well as the closely related JSON Web Token (JWT) specification.

Technologies used:

  • Apache Maven 3.0.5
  • Nimbus JOSE+JWT 2.16
  • Java 7


First, let’s add maven dependency for Nimbus JOSE+JWT lib:



…and start composing the JWT reserved claims right away:

JWTClaimsSet jwtClaims = new JWTClaimsSet();
List aud = new ArrayList<>();
jwtClaims.setExpirationTime(new Date(new Date().getTime() + 1000*60*10));
jwtClaims.setNotBeforeTime(new Date());
jwtClaims.setIssueTime(new Date());

as you can see, we’re setting up all of the Reserved Claim Names mentioned in my earlier post on JWT (ie. Issuer, Subject, Audience, Expiration Time (to 10 minutes), Not Before Time, Issued At Time and the JWT ID) and using random UUID as the identifier of the token.


When printed out the above, you should see something similar to this:



now, let’s create the JWT header and specify RSA-OAEP as the encryption algorithm and 128-bit AES/GCM as the encryption method that will be used to protect the JWT token:

JWEHeader header = new JWEHeader(


next create the EncryptedJWT object that will be later used to perform the RSA encryption:

EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);


…create an RSA encrypter with the specified public RSA key:

RSAEncrypter encrypter = new RSAEncrypter(publicRsaKey);

(for details on how to generate RSA keys, please read my post on “RSA Keys Generation”)


and do the actual encryption:



finally, we can serialize to JWT compact form in order to print it out to the screen nicely:

String jwtString = jwt.serialize();


what you should see after performing the steps above, is something similar to this:



Now, if you’d like to read the data back from the token using your private RSA key, you’d have to do the following:

parse the above JWT string using EncryptedJWT object:

EncryptedJWT jwt = EncryptedJWT.parse(jwtString);


create a decrypter with the specified private RSA key:

RSADecrypter decrypter = new RSADecrypter(privateRsaKey);


do the decryption:



and print out the claims:

System.out.println("iss: " + jwt.getJWTClaimsSet().getIssuer());
System.out.println("sub: " + jwt.getJWTClaimsSet().getSubject());
System.out.println("aud: " + jwt.getJWTClaimsSet().getAudience().size());
System.out.println("exp: " + jwt.getJWTClaimsSet().getExpirationTime());
System.out.println("nbf: " + jwt.getJWTClaimsSet().getNotBeforeTime());
System.out.println("iat: " + jwt.getJWTClaimsSet().getIssueTime());
System.out.println("jti: " + jwt.getJWTClaimsSet().getJWTID());


resulting with the following output:

sub: Mariusz
aud: 2
exp: Fri Jul 12 12:32:40 CEST 2013
nbf: Fri Jul 12 12:22:41 CEST 2013
iat: Fri Jul 12 12:22:41 CEST 2013
jti: c79772ea-8777-44dc-a0fe-9001aeee9d02



If you’re interested in a complete source code of this example, please clone the following Gist available on my GitHub account.





JWT (JSON Web Tokens)

While working on one of the security-related aspects of the platform i’m building, i came across JWT specification which i find very interesting and thought will share with you the notes i made while reading:


  1. JWT acronym stands for “JSON Web Tokens”.
  2. Definition of a security token:
    • encrypted data structure (in this case of JSON format) which contains:
      • information about the issuer and subject (claims)
      • proof of authenticity (digital signature)
      • expiration (validity) time
  1. Suggested pronunciation of JWT is the same as the English word “jot”.
  2. Basic facts:
  1. Why JSON-based standard?
    • XML-based SAML data format, exchanged over SOAP protocol offered a ton of encryption and signature options but was percieved as a “heavy” technology and of not much use by mobile appliance (initially not that strong in terms of computing power). JSON messages on the other hand don’t require a fairly advanced technology stack (like SAX, StAX, etc.) to produce and parse data structures and can be exchanged over HTTP (also, each browser nowadays is supporting JavaScript).
  1. Characteristics:
    • Plaintext JWTs: support use cases where the JWT content is secured by means other than a signature and/or encryption contained within the JWT. A plaintext JWT has the header “alg” parameter value set to “none”.
    • Encrypted JWTs: use JSON Web Signature (JWS) and JSON Web Encryption (JWE) to sign and/or encrypt the contents of the JWT using JSON Web Algorithms (JWA)
    • symmetric (HMACSHA256-384) and asymmetric (ECDSA, RSA) signatures
    • symmetric and asymmetric encryption (RSA, AES/CGM)
  1. Structure:
    • JWT Header
      • metadata
      • algorithms & keys used
    • JWT Claims
      • Reserved Claim Names:
        • “iss” (Issuer)
        • “sub” (Subject)
        • “aud” (Audience)
        • “exp” (Expiration)
        • “nbf” (Not Before)
        • “iat” (Issued At)
        • “jti” (JWT ID)
        • “typ” (Type)
      • Public Claim Names
      • Private Claim Names
  1. Example:
// header object

// claims object

    // additional public claims
    "scope":["read", "search"],
    "client":"system A"

In the example above, the JWT Header implies that the encoded object is a Plaintext JWT. Additional public claims, may be useful for example in oAuth protocol (to know which system (A in this case) requested the token and what operations (read, search) will it be authorized to perform using this token).

  1. Sample encoding:
    • Base64url encoded representation of the JWT Header:
      • eyJhbGciOiJub25lIn0
    • Base64url encoded representation of the JWT Claims Set:
      • eyJleHAiOjEzNzM2NDI3NzYsInN1YiI6Ik1hcml1c3oiLCJuYmYiOjEzNzM2NDIxNzYsI


Complete JWT is a result of concatenating encoded representations of the header and the claims set with a period (‘.’) character between the parts:

  • eyJhbGciOiJub25lIn0.eyJleHAiOjEzNzM2NDI3NzYsInN1YiI6Ik1hcml1c3oiLCJuYm


Finally, the above string representation of a JWT security token is what gets transmitted over the wire as a message header or url query parameter.




JavaScript Toolset

Below you’ll find a short list specifying toolset that may be helpful when developing JavaScript code:

  1. Node.js – a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
  2. NPM – node package manager (part of Node.js)
  3. Yeoman – a robust and opinionated client-side stack, comprising tools and frameworks that can help developers quickly build web applications
  4. Bower – package manager for javascript libraries
  5. Karma – Spectacular Test Runner for JavaScript
  6. WebStorm – The smartest JavaScript IDE
  7. Jasmine – a behavior-driven development (BDD) framework that allows writing specifications that denote how your code should behave.
  8. Batarang – Extends Chrome’s Developer Tools, adding tools for debugging and profiling AngularJS application
  9. RequireJS – a JavaScript file and module loader


Also, there are tools you’ll be using less frequently (especially, if you decide to go with Yeoman as Yo integrates many of them), but still it’s good to know what they do:

  1. angular-seed – seed project (an application skeleton) for angular apps. You can use it to quickly bootstrap your angular webapp projects and dev environment for these projects. The seed contains AngularJS libraries, test libraries and a bunch of scripts all pre-configured for instant web development gratification. Just clone the repo (or download the zip/tarball), start up our/provided (or yours) webserver and you are ready to develop and test your application.
  2. underscore.js – a utility-belt library for JavaScript that provides a lot of the functional programming support for the usual functional suspects (each, map, reduce, filter…) without extending any core JavaScript objects.
  3. angular-mocks.js – contains an implementation of mocks that makes testing angular apps easier.
  4. angular-scenario.js – a nifty JavaScript lib that allows you to write and execute end-to-end tests for angular applications
  5. angular-loader.js – module loader for Angular modules. If you are loading multiple script files containing Angular modules, you can load them asynchronosuly and in any order as long as you load this file first.
  6. angular-resource.js – provides $resource service that makes it possible to execute HTTP calls (eg. against REST API’s)
  7. angular-cookies.js – provides two services: $cookies and $cookieStore.
  8. angular-sanitize.js – provides ngBindHtml directive, linky filter and $sanitize service.

Starting with AngularJS

There’s a lot of places on the internet where you can go and read about AngularJS, but to set some framework for the journey i prepared a short list of most useful links.

  1. – Google’s superheroic JavaScript MVW Framework
  2. – great way to get introduced to AngularJS
  3. – neat things built with AngularJS
  4. – the companion suite(s)
  5. – bootstrap components written in pure AngularJS
  6. – angular modules
  7.…/angularjs-batarang – AngularJS WebInspector Extension for Chrome
  8. – great video tutorial
  9. – news on the framework
  10. – videos
  11. – tweets
  12.…/angular – forum discussions
  13.…/JSFiddle-Examples – useful fiddles, gists, plunkers collected from forum discussions
  14.…/angularjs – questions and solutions
  15. – meetup groups
  16.…/angularjs – cheat-sheet