Saturday 11 April 2020

JWT v/s [Session] Cookies


What is this new JWT thing? 

Does it replace the usual session-cookie?

How complicated is this thing called JWT?


This were the questions that were lingering on my mind when I wanted to get the API-system's authentication renewed. I have been hearing about JWT , and wanted to figure out what was it and how was it better. 

JWT ,  "J-awt" as they call in some circles, in a layman's language is a mechanism to store some arbitrary data, but is so structured that the JWT can also authenticate that the data has not been changed by a third party ( remind's me of block-chain, but it is a distributed ledger and thankfully JWT is not as complicated as that ).

Once we know the data integrity cannot be compromised, a server could issue it to the client and the client henceforth could use it for dealing with server, and providing the JWT to the server in any communication is a simple way of client to claim the rightful resources. One can imagine JWT to be some sort of access card given to employees by the employer during the on-boarding. After that, employee could use it to access the office and the other places as designated by the employer.

Isn't this what was session-cookie was also designed to do. Uhmm yes, but here we need to digress , a cookie is a mechanism for a HTTP-Client-Server to keep some underlying information. It is send as a part of every transmission once it is set. Session-Cookie is the name given when we used to store session-token in the cookie. The session-token used to be a token with a database entry and would have permissions listed against it. Just like the employee badge. Every time access request comes, the session token is extracted from the cookie, compared against the database ( or some storage ) and authorized. This is a tedious process since if every access is validated against DB , it would form the bottleneck. This is the kryptonite for session-tokens ( or session-cookies ).

JWT evolved to solve this by not needing the server to say hello to the DB for every single request. It could easily hash out the validity and find the authenticity. So the requests are not throttled by a DB, but this can be beneficial to a micro-service based architecture where every micro-service could understand the token and need not check up with a separate auth service to check the authenticity of the token. Sounds cool, isn't it?,  but there is a drawback, remember - earlier I had said about employee and access-badge?, the session-token is a proper badge. If there is a rogue employee or if someone loses the badge, we can disable it electronically. But the JWT is like a dress/uniform or a name-plate. If some steals ( copies it ), they would also be authorized to do everything that the real user was intended to do. OOPS!

There are some protection which can be done against this problem as well. But that's for a separate blog. 

To summarize, JWT provides for scalable way of authorizing clients, session-tokens provides more control. JWT for speed , session-tokens for security.

In the end - JWT can be stored in cookies , and session-tokens can be sent without any cookies. 

Wednesday 1 August 2018

Starting off with NGINX-UNIT

I am intending to write down some of the things I encountered as I set myself into running an app in NGINX-unit. 

Selling Points/USP

  1. Ease of installation
  2. Performance
  3. Changing the applications without needing to bringing down the server and server taking care of the connections while this process happens
  4. Ease of doing configurations -> via json using http calls 

Problem with Prefix. ( comes across as make install error)



root@netarch-ci-webserver:/home/ubuntu/unit-1.3# make install

error: to make install you need either
    to configure --prefix option
    or to set DESTDIR environment variable.

build/Makefile:1414: recipe for target 'install-check' failed
make: *** [install-check] Error 1


Solution:

Set the prefix to whatever you wish to while running 'configure' using the --prefix PATH.  I set it as '/' . , so the unitd goes and resides in /sbin on 'make install

Saturday 18 November 2017

Modal in a Bootstrap Angular 4 application using ng2-bootstrap-modal

Note: This is for folks not using the angular-bootstrap.


Challenge:

The usual javascript libraries would not integrate very well with the other Angular components. I needed the modal to take up arguments from the parent component and also pass back information to the parent once it has done a AJAX call ( HTTP-Post ). The main challenge I did face was documentation which was not available in one place.

Library Used:

ng2-bootstrap-modal  from ( https://www.npmjs.com/package/ng2-bootstrap-modal )

To Start:

  1. Get the NPM module installed.

-> npm install https://www.npmjs.com/package/ng2-bootstrap-modal



      2. Create the Modal Component required for your purpose

-> ng generate component myModal  ( this will add the component to app.module.ts as well )

      3. Changes in the app.module.ts


-> import { BootstrapModalModule } from 'ng2-bootstrap-modal';

-> Add "BootstrapModalModule" in the imports

-> Add your component to the entryComponents under the NgModule using:
     entryComponents: [MyModalComponent]

     4. Changes in myModal.component.ts

->  Add : import { DialogComponent, DialogService } from "ng2-bootstrap-modal";

-> Create the interface  and export
export interface MyModel {
  idList: number[];
  title:string;
}

-> Change the myModalComponent to extend the dialogComponent
export class MyModalComponent extends DialogComponent<MyModel, number> implements MyModel{ 
  idList: number[];
  title:string;

-> Have the constructor extend the DialogService using super() call
  constructor(dialogService: DialogService) {
    super(dialogService);
    this.jobId = 0;
  }

-> Create a close function and also functions for the different actions in the modal as required and link it to the html just like any other constructor. The important thing to remember here is to have this.result set to the result and to close() the modal once the action is done.

  cancel() {
    this.result = -1;
    this.close();
  }


    5. Changes to the calling component

-> Import the dialog service
import { DialogComponent, DialogService } from "ng2-bootstrap-modal";

-> Import the modal Component
import {MyModalComponent} from '../my-modal/myModal.component';

-> In the click function where we need the modal to appear, add this line to call the Dialog-Component with the necessary arguments //CheckStatus is my click call-back
 checkStatus() {
    this.dialogService.addDialog(MyModalComponent,{idList:[1,2,3], title: 'Availability'});

  }


Thursday 11 September 2014

PostMan Chrome App: A web developer's light saber

Updates:
Postman is no more a Chrome App, it runs standalone which I think is nicer. The functionality has not changed much. I use it more nowadays and I intend to use the collections for testing of my organisation's  API system in future. I also love the fact that I can store the response from my previous API calls so that I can have a snapshot store.
  
Now to the original post


Tall claim perhaps

But in two days of using this tool, this has become an indispensable tool in my arsenal and I am kicking my back for not using this tool before. Thanks to the guys stack-overflow who pointed me into this direction.

A little bit about the tool: It helps in developing and debugging those web-api's without need of developing clients for that. A REST Client to see how your REST API behaves on the various inputs.

Installing is a breeze.

The interface is super simple. It would take in the URI of the API and the type of request.  Now according to the API, we can provide variety of inputs. 
For form-type input the tool provides a neat interface to do where we can provide key-value pair and even allows file attachment (Big Relief)
For JSON ( which has become almost indispensible with AJAX calls ), you choose the "raw"type input and an additional selection on what type of raw input gives the option for JSON. 

Press SEND to get it running and the results are displayed below the input given. 

The tools also stores history of the REST calls made and that makes it easier to create complicated inputs in a progressive manner. Any comments on better tools like this would be so much appreciated.


Monday 3 February 2014

The swiss-army knife of dropdowns .. from the same guy that runs A Beautiful Site, LLC. and Surreal CMS.

I had a challenging project to do for the client and the site cried out for aesthetics as well as functionality. Initially I was playing around with bootstrap button-dropdowns. 



The limitations of CSS provided by bootstrap meant that I had my button group magically shrinked when the dropdown came in and the placement was just not correct. I did not want to bother with CSS for that since I anyway had my hands full. It is at this point I thought of looking out for a better solution and bingo, i found it at : http://labs.abeautifulsite.net/jquery-dropdown/ with the downloads available at : https://github.com/claviska/jquery-dropdown.

So what makes it different?. The biggest thing is that now I am able to put HTML into my dropdowns!!.. yayyy.. The styling is taken care off and i can control the dropdown using API's provided alongside. 

With the ability to put HTML , i made use of buttons to set the job instead of list. 
With styling headache gone, it freed my time.  
The APIs gave me much finer control to pop up and to remove elements as I needed!.

Now the changed page looks like this.. aint this awesome!. Thanks to the developers of this smart dropdown!.

 

Saturday 18 January 2014

Bootstrap fixed-top-navbar: Solving the challenge of having Links within page position correctly


  This is more or less a Bootstrap primer. There were different solutions available, but the basic issue was that off the Title of the link hiding itself under the navbar. My header went and hid itself under the navbar as shown in picture.


The usual technique as advised by Bootstrap was to have padding in the body when adding fixed-top-navbar. But that would not work in this case unfortunately. Also having a big padding to offset the navbar for every heading would create lot more spacing than I would like to have. 

The solution which worked for me was to add spacing as and when the user clicks the link to navigate to that section. I used a mix of jQuery and CSS magic for this along with slightly changing the way I wrote the HTML. I made changes so that a jQuery function can formulate the id dynamically from the button name itself. In my case I just removed the white spaces and hey presto!.. I have the id to the section where I need to go to :-).

First of all I enclosed my header tags into another div and put it under page-header class. This is a class which is available in the Bootstrap itself. But I believe you can put any arbitrary class which suits the structure. 

The next step is to make the css for the "active" page-header ( which is the one clicked by user ) have a padding which would show title below the navbar. So i created a rule in CSS so that the "page-header active" would have enough spacing. 
The last stage is to have a jQuery function call onto the anchor/button click event so that it does some magic. The steps done are
(i) Remove the active tag from all the buttons of the same class.
(ii) Set the active tag to the button on which click event has registered
(iii)  Parse the name of the button and form the target id.
(iv) Set the padding of destination
(v) Go to location using jQuery
This worked for me elegantly, hope this helps you too or gives ideas to have more amazing stuff created.

Sunday 12 January 2014

Google map(v3) into bootstrap modal-3.0

Having a Google-map into Bootstrap-3.0 Modal

"It is a given that any competent business landing-page should have a map"
This is a short description to help setup the google-map into a modal when using Bootstrap-3.0. I also use jQuery in the front end. Bootstrap uses jQuery by default, so in case you are using Bootstrap framework it is always to learn a beginner level of jQuery to make life easier!.

This is heavily "inspired" from Google's own tutorial and another better tutorial from Google.

The first step is to create a <div></div> which would house the map. Provide an id of your choice. For the tutorial purpose I named it "map_canvas".

Let us now place the <div> node into the modal under the <div class="modal-body">. So the html should look like:

 

Now get the styling elements for this ready in a .css file or inside html itself. The height and width of the element should be clearly defined. Defining a non-white color background is very useful during testing. So my CSS code would look like:

At this point, loading the html should give you a grey box. Now let us get into the fun part. Lets load the js file for the google map api's. From my little observation, i noticed this weird fact that the js file worked only when it is in the <head> node. Please add this to the head node.

To get the map displayed in the map canvas we need to call initialize the google.maps.Map function and to get a marker to show the location we need google.maps.Marker objects. For simplicity sake I enclosed both of them in a function named initialize. The list of options to control the Map can be accessed from this document.

This function needs to be called when the modal is being rendered. Bootstrap provides a neat little trigger in name of 'shown.bs.modal'. Combining the two the js code would look like:

We can find the necessary latitude and longitude from google maps from here. Now zoom in and out to find the zoom level you are comfortable presenting and there you go!. You should be seeing the maps in the modal as it pops up.

There are cases when the zoom-bar doesn't show up properly. This is due to the default 'max-width' attribute for the img and needs to be adjusted for the map_canvas. The final CSS:


Hope you are successful in embedding maps into your modals for a better user experience. I shall explore advanced aspects of displaying maps later on, but comments are welcome.