Friday, December 16, 2016

What is JSON Web Token?

1. Overview

JSON Web Token or JWT (jot) for short is an open standard (RFC 7519) that defines a compact, URL-safe means of representing claims to be transferred between two parties.  The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

2. Structure

The compacted representation of a signed JWT is a string that has three parts, each separated by a dots (.) :

Eg: 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0
.
Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI

Each section is Base64Encoded and the first section is called header, the second section is payload and the third section is Signature.

2.1 Header

It consists of two parts: Hashing algorithm (HMAC SHA256 or RSA) and type of the token and to form the first part of the JWT, you need to do Base64Url encoded.

Eg:
{
  "alg": "HS256",
  "typ": "JWT"
}


2.2 Payload

Payload contains the Claims. JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT i.e. Data to be shared between the applications.
Eg:
{
  "sub": "Abdul",
  "iat": 1234567890,
  "exp": 1234567890,
  "nbf": 1234567890,
  "iss": "http://waheedtechblog.in",
  "scope": ["read","write"],
  "admin": true
}

There are three types of claims: reserved, public, and private claims.

2.2.1 Reserved Claims

These are standard predefined claims defined in the specification which can be used to provide a set of useful claims. Some of them are : 
a. "iss" (Issuer) Claim
b. "sub" (Subject) Claim 
c. "aud" (Audience) Claim
d. "exp" (Expiration Time) Claim
e. "nbf" (Not Before) Claim
f. "iat" (Issued At) Claim
g. "jti" (JWT ID) Claim  


2.2.2 Public Claims

These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.


2.2.3 Private Claims

  All the custom claims come under private claims and it is created to share information between parties that agree on using them.
{
"scope": ["read","write"],
 "admin": true
}

2.3 Signature

To create the signature part, you have to take the encoded header, the encoded payload, and a SECRET_KEY, the algorithm specified in the header, and sign that.
Eg:
if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

You will get the below JWT token if you combine above header and payload and will use secret as SECRET_KEY.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0.Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI


3. How do JSON Web Tokens work?


1. Browser will log in to Authorization Server via username/password

2. Authorization Server will authenticate the user and will create the JWT token signed by its key and will return in the response.
3. Now, Browser will access the Application Server by JWT token as Authorization bearer <token> in the header.
4. Application Server will verify JWT using secret key (In such scenario, Key must be shared between Authorization Server and Application Server), Decode the String, verify the claims and will return the response.


4. Open Source libraries:

There are already open source libraries available in the market using which you can create and verify the access token. 
Source code for implementation of above library can be downloaded from GITHUB

5. Conclusion:

We went over what JWT are, how they are created and validated, and how they can be used to ensure trust between an application and its users. This is a starting point for understanding the fundamentals of JWT and why they are useful. 

6. References:



Friday, December 2, 2016

@Embeddable and @Embedded in Hibernate Annotation

Before jumping to @Embeddable and @Embedded annotation. Let me explain about hibernate different objects:
        Entity Object
o   Entity object are those object which can stand alone like Student or Professor and has its own database identity.
        Value Object
o   Objects which cannot stand alone like Address as you need to map address with some Entities like Student. It will belongs to an entity, and its persistent state is embedded in the table row of the owning entity

In short, always use @Embeddable for the value object and @Embedded with the entity class.

Let's understand it by a simple example:

We have one Address (Value object) and it is having attributes like city, state, zip code. Now we have two more different entity Student and Professor (Entity Object). Student or Professor can have Address attributes just by embedding the Address into its Entity.

The @Embedded annotation is used to specify the Address entity should be stored in the STUDENT table as a component.

@Embeddable annotation is used to specify the Address class will be used as a component. The Address class cannot have a primary key of its own, it uses the enclosing class primary key.



Download the source code of this example from Github.

You will see the output once you execute the Application class from source code


and will create the following tables in the database



Happy Coding..!!!

What is MappedSuperClass in hibernate ?

MapperSuperClass


·        A mapped superclass has no separate table defined for it.
·        Designates a class whose mapping information is applied to the entities that inherit from it. 
·        A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. 
·        When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. 
·        Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.
·        It avoids the code repetition like adding an id, version or timestamp fields in every Hibernate entity.

Example:

AbstractEntity.java class having MappedSuperClass but no Entity annotation.





User Class extends AbstractEntity class and will persisting user object, it will also persist Id and other details of mapped Class.



You can download the whole source code for Github.

After running the query, Attributes of AbstractEntity class will get created under 'USER' table.


Happy Coding...!!!

Monday, November 28, 2016

MongoDB basic Overview

Overview

  • MongoDB is a cross-platform, documented oriented database and it is not based on schema like relational database.
  • It uses dynamic schema and stores data in JSON format.
  • It provides high performance, high availability, and easy scalability and it works on concept of collection and document.
  • It is an open-source software.
  • MongoDB is mainly written in C++, JavaScript and C.


Download

Please refer this link to setup MongoDB on your machine.

Terminology

·         Document

Document is similar to row/tuples in RDBMS, it is a set of key-value pairs and having dynamic schema i.e. the documents in the same collection do not need to have the same set of fields or structure and another document may hold different types of data.

·         Collection

It is the equivalent to a TABLE in RDBMS and do not enforce a schema. It exists within a single database and each document within a collection can have different schema.

·         Database

It is the equivalent to a DATABASE in RDBMS and a database can have zero or more collections.


Sample Document

{ "_id" : ObjectId("583c623e2226aa5f3b8e14f4"),
"title" : "MongoDB Basic Overview",
"by" : "http://waheedtechblog.in"
}

Where _id is the unique key for each document generated by MongoDB. Even we can provide unique key in MongoDB by specifying _id attribute while inserting data.
The generated unique key has specific format i.e. first 4 bytes are for the current timestamp, next 3 bytes are for machine id, next 2 bytes are for process id of MongoDB server and last 3 bytes are simple incremental VALUE. 

Advantages of MongoDB

· It is a schema less document
· No more complex joins
· Provides ACID properties at the document level as in the case of relational databases.
· Supports common authentication mechanisms, such as LDAP, AD, and certificates. Users can connect to MongoDB over SSL and the data can be encrypted.
· Enables horizontal scalability by using a technique called Sharding.
· Supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL.
· Conversion/mapping of application objects to database objects not needed.
· Cost effective solution as it improves flexibility and reduces cost on hardware and storage.
· Supports replica sets i.e. a failover mechanism is automatically handled. If the primary server goes down, the secondary server becomes the primary automatically, without any human intervention.

When to Use MongoDB Rather than MySQL or any Other RDBMS

· When your data is going to big and schema is not defined.
· When your data is location based
· When you expect a high load
· When you need to partition and shard your database.
· When you want to create, replica set (set of servers that act as Master-Slaves) 


Summary

MongoDB is great tool and can be very useful in creating applications like bug tracking, discussion forums, advertisements, and the like. However, Joins are not possible in MongoDB; It requires proper analysis before making a decision.

Sunday, November 27, 2016

How to install and verify MongoDB on Windows 7 ?


Step by Step instructions:

1.      Download MongoDB

Check MongoDB msi from Official website and download Windows Server 2008 R2 64-bit and later version.

2.      Install MongoDB

Double click on downloaded MSI (mongodb-win32-x86_64-2008plus-ssl-3.2.11-signed.msi) file and follow the click on next button on wizard to complete the installation.

3.      Create Default Directory

MongoDB requires a data directory to store all data and its default data directory path is \data\db.
On Windows, By default it will always look for above directory under C:/ structure, Goto C: directory and create /data/db, So the full path of db folder will be C:\data\db

4.      Set environment variables

Set MongoDB location to system's environment variables and give path till bin folder.

5. 

5.      Start MongoDB

To start MongoDB server, Open cmd and type mongod, it will start the MongoDb server on port -27017.


6

6.      Verify MongoDB

Open cmd prompt and type mongo.exe

Additional Notes:


 1.      Configuration File

We can create a config file where we can add the custom path of data/db directory, Config file will be similar to properties file and add attributes in key/value pair.
##data path can be updated using dbpath
dbpath=E:\mongodb\data

##log file
logpath=E:\mongodb\log\mongo.log

Use mongod.exe –config E:/mongodb/mongo.config to load config file while starting mongodb2. 

2.      Start as a service

We can start mongoDB as a service, Adding MongoDB as Windows Service will start MongoDB automatically following each system restart. Install as Windows Service with --install.
E:\mongodb\bin> mongod --config E:\mongodb\mongo.config --install


To start MongoDB Service
net start MongoDB


To stop MongoDB Service
net stop MongoDB

To remove MongoDB Service

d:\mongodb\bin>mongod --remove

Thank you..!!!

Monday, May 2, 2016

How to extract Private key from keystore ?

There can be a situation where you want to extract private key from your keystore but it is not a straight forward as we think as It involves two steps i.e.
·         Extracting private key from keystore in PKCS#12 format
·         Converting it to .PEM file

Step1: Extracting in PKCS format
keytool -v -importkeystore -srckeystore KEYSTORE_NAME -srcalias CERTIFICATE_ALIAS -destkeystore FILE_NAME.p12 -deststoretype PKCS12
Eg: keytool -v -importkeystore -srckeystore keystore.jks -srcalias  application -destkeystore privatekey.p12 -deststoretype PKCS12

Note: If you don’t know the alias name of your certificate then you can display it:
keytool -list -v -keystore keystore.jks
Step2: Converting it into .PEM FILE
openssl pkcs12 -in privatekey.p12 -out private.pem

            

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...